Lab 19: HTTP PUT
Objectives
- Communicate with a REST API to update data
Steps
Communicate with a REST API to update data
Implement a method in the API object to do a PUT (update).
src\projects\projectAPI.js
...const projectAPI = {...+ put(project) {+ return fetch(`${url}/${project.id}`, {+ method: 'PUT',+ body: JSON.stringify(project),+ headers: {+ 'Content-Type': 'application/json'+ }+ })+ .then(checkStatus)+ .then(parseJSON)+ .catch((error) => {+ console.log('log client error ' + error);+ throw new Error(+ 'There was an error updating the project. Please try again.'+ );+ });+ },};Invoke the method in your container (
ProjectsPage
) component.src\projects\ProjectsPage.js
+ import { Project } from './Project';...function ProjectsPage() {...const saveProject = (project) => {- let updatedProjects = projects.map((p) => {- return p.id === project.id ? project : p;- });- setProjects(updatedProjects);+ projectAPI+ .put(project)+ .then((updatedProject) => {+ let updatedProjects = projects.map((p) => {+ return p.id === project.id ? new Project(updatedProject) : p;+ });+ setProjects(updatedProjects);+ })+ .catch((e) => {+ setError(e.message);+ });};return (...);}export default ProjectsPage;Verify the application is working by following these steps.
- Click the edit button for a project.
- Change the project name in the form.
- Click the save button on the form.
- Verify the card shows the updated data.
- Refresh your browser.
- Verify the project is still updated.