Saul
Saul

Reputation: 311

State not updating correctly with get request from API

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.

Upvotes: 0

Views: 387

Answers (3)

LiranC
LiranC

Reputation: 2480

Assuming that categories is an array, you are overriding one array with another array.

In the code below, i am always returning a new array, and concating the new array with the previous array.

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

Upvotes: 0

Andrii Starusiev
Andrii Starusiev

Reputation: 7764

First of all, your spread operator is wrong, you have to wrap it into array categories: [...this.state.categories, ...res.data.data]. Also I advice you to wait all your post loaded and then set them to state:

Promise.all([axios.get('LINK_TO_API'), axios.get('LINK_TO_API_2')])
    .then(allYourPosts => {
        this.setState({ /* set it to state */ });
    })
    .catch((error) => {
        console.log(error);
    });

Upvotes: 0

F.bernal
F.bernal

Reputation: 2684

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);
  });

Upvotes: 1

Related Questions