Ad

State Not Updating Correctly With Get Request From API

- 1 answer

I am making two api GET requests, and with both I would like the state to update. For some reason it is only updating with the values from the first GET request.

I have tried using the spread operator to update the state and add in new values to current state (categories) from the GET requests.

axios // first get request
  .get(
    "LINK_TO_API"
  )
  .then(res => {
    this.setState({
      ...this.state.categories,
      categories: res.data.data
    });
  })
  .catch(function(error) {
    console.log(error);
  });
axios // second get request
  .get(
    "LINK_TO_API"
  )
  .then(res => {
    this.setState({
      ...this.state.categories,
      categories: res.data.data
    });
  })
  .catch(function(error) {
    console.log(error);
  });

I am currently getting 10 values from first GET request and would like to get the total of 20 values when I map through categories.

Ad

Answer

You will never get 20 values, due to are not appending values, you just are overwriting categories values in each call.

this.setState({
  ...this.state.categories,
  categories: res.data.data
});

Here categories: res.data.data is being overwrited.

Just modify your code to:

 axios
  .get(
    "LINK_TO_API"
  )
  .then(res => {
    this.setState((state) => ({
      ...state,
      categories: [...state.categories, ...res.data.data]
    }));
  })
  .catch(function(error) {
    console.log(error);
  });
Ad
source: stackoverflow.com
Ad