简体   繁体   中英

How to update data in ReactJS using JSON server

I am new to react and I can fetch the data from JSON file . Now I need to update those values and submit to the JSON file . I am struggling to submit updated input field in JSON file

 submitEmpData(event) {
    event.preventDefault();
    this.state.empProjects.allocation=this.state.allocation;
      this.setState({
        empProjects:this.state.empProjects
      });
    return fetch('http://localhost:3000/Employee/' + this.state.empProjects.id, {
        method: 'PUT',
        mode: 'CORS',
        body: this.state.empProjects,
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => {
        return res;
    }).catch(err => err);
  }

There are some ways to trigger a render in react:

You send new values down as props to a child component, or

You use a form of state (hooks or setState for example) to update a components state.

In your example, add a setState once the fetch promise has either rejected or resolved, setting the data needed for rendering.

I have restructured the code for better understanding. I believe JSON.stringify() and res.json() may places where you might need to look into.

async submitEmpData(event) {
  event.preventDefault();

  let { empProjects, allocation } = this.state;

  empProjects.allocation = allocation;

  // updating the state
  this.setState({
    empProjects,
  });

  // calling the api
  try {
    let res = await  fetch("http://localhost:3000/Employee/" + this.state.empProjects.id, {
      method: "PUT",
      mode: "CORS",
      body: JSON.stringify(this.state.empProjects),
      headers: {
        "Content-Type": "application/json"
      }
    })
    return await res.json();
  } catch (err) {
    return err;
  }
}

Kindly ping me in comments for any clarification

The following method is wrong to change the JSON because the this.state is an object and javascript will check the reference for comparison ( See this ).

 this.state.empProjects.allocation=this.state.allocation; this.setState({ empProjects:this.state.empProjects });

instead of this, you can use the spread operator to create a new object:

this.setState({
   ...this.state, this.state.empProjects: { ...this.state.empProjects, allocation: "NEW value"}
})

Also to send the request using fetch, the body must match with content type :

body: JSON.stringify(this.state.empProjects)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM