Skip to main content

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.ts


    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.'
    + );
    + });
    + },

    };
  2. Invoke the method in your container (ProjectsPage) component.

    src\projects\ProjectsPage.ts

    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) => {
    + if (e instanceof Error) {
    + 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