Skip to content

Latest commit

 

History

History
93 lines (71 loc) · 2.09 KB

19-HTTP-PUT.md

File metadata and controls

93 lines (71 loc) · 2.09 KB

Lab 19: HTTP PUT

Objectives

  • Communicate with a REST API to update data

Steps

Communicate with a REST API to update data

  1. 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.'
    +        );
    +      });
    +  },
    
    };
  2. 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;
  3. Verify the application is working by following these steps.

    1. Click the edit button for a project.
    2. Change the project name in the form.
    3. Click the save button on the form.
    4. Verify the card shows the updated data.
    5. Refresh your browser.
    6. Verify the project is still updated.

image


✔ You have completed Lab 19