0
votes

I'm currently working on a React app where I'm using React's context API to put together the business logic of the app.

Inside the context all CRUD functions make axios requests to the API and return promises that can be used by components to deal with error handling and input. This is the context https://github.com/luckyrose89/notes-app/blob/master/src/AppContext.js

My app has a notebooks array that will contain individual notebook objects. And each of these objects has a notes array that refers to the notes made in each notebook. This is the APIs controller https://github.com/luckyrose89/notebook-app-backend/blob/master/controllers/notebook.js

As long as I was creating, reading, updating and deleting the notebooks, I had to make changes to the state in app context for things to get updated in my app. But when I create, read, update or delete anything in the notes array of the notebooks, I do not have to make those changes to the state. I return the promise and the state changes on its own. Can anyone help me understand why is this happening?

For example when I create a new note in a notebook and submit it using this:

handleSubmit = event => {
event.preventDefault();
this.props
  .createNotepage(this.props.match.params.id, this.state)
  .then(response => {
    this.clearInputs();
    this.props.history.push("/viewbooks");
  })
  .catch(err => {
    this.setState({
      errorMessage: err.response.data.error
    });
  });};

I don't have to change the state in the app's context by manually adding the response from the api to the notebook's notes array. Can anyone please explain this.

1
I don't quite understand your question. Aren't you calling setState after each operation, which will update the state, and the value of the Provider will change, which will cause all consumers to update?Tholle
@Tholle I'm not calling setstate after operations that are performed on the notepages. I access those operations in the components and give them relevant arguments. My question is that how is the notebooks array in app context getting updated on its own without me making changes to the state once a note is added, updated or deleted in a notebook object within the notes array. I'm really sorry for the confusion hereDivya Mathur

1 Answers

0
votes

instead of passing this.state, try passing {...this.state} and see what happens