Ad
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.
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
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad