magnat magnat - 7 days ago 6
React JSX Question

Promise.all result fires before actions succeed

I'm searching and searching solution on Stackoverflow and Github but 1.5 day is not enough - I don't see where I'm making mistake. I have following code of my component where I would like to fetch data from two endpoints and after store updates I console log something.

class ExampleComponent extends Component {
componentDidMount(){
this.fetchData()
}

fetchData(){
const {dispatch} = this.props
Promise.all([
dispatch(getTodos()),
dispatch(getPhotos())
])
.then(() => {
console.log('I did everything!');
});

}
render() {
return (
<h1>Something</h1>
);
}
}

export default connect()(ExampleComponent)


And here are my actions...

export function getPhotos() {
return function(dispatch) {
axios.get('https://jsonplaceholder.typicode.com/photos')
.then((response) => {
console.log('photos')
dispatch({type: 'PHOTOS_REQUEST_SUCCESS',payload: response})
})
.catch((err) => {
dispatch(photosRequestError(err))
})
}
}

export function getTodos() {
return function(dispatch){
axios.get('https://jsonplaceholder.typicode.com/todos')
.then(
(response) => {
console.log('todos')
dispatch({type: 'TODOS_REQUEST_SUCCESS', payload: response})
})
.catch((err) => {
dispatch(todosRequestError(err))
})
}
}


In console I get "I did everything", "todos", "photos". How should I modify my code to update store first and then log "I did everything" in console?

Thanks in advance

Answer

You need to return the promises themselves so that the chaining apply synchronous, so try adding return to axios.get('endpoint/url') in both functions.