- Communicate with a REST API to update data
-
Implement a method in the API object to do a PUT (update).
import { Project } from './Project'; ... const projectAPI = { ... + put(project: Project) { + return fetch(`${url}/${project.id}`, { + method: 'PUT', + body: JSON.stringify(project), + headers: { + 'Content-Type': 'application/json' + } + }) + .then(checkStatus) + .then(parseJSON) + .catch((error: TypeError) => { + 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.import { Project } from './Project'; ... function ProjectsPage() { ... const saveProject = (project: Project) => { - let updatedProjects = projects.map((p: Project) => { - return p.id === project.id ? project : p; - }); - setProjects(updatedProjects); + projectAPI + .put(project) + .then((updatedProject) => { + let updatedProjects = projects.map((p: Project) => { + 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.