Answer the question
In order to leave comments, you need to log in
How to wait for a response from the server when doing dispatch in Promise.all using axios, redux?
Good day to all. I'm writing a small app in react/redux and axios in which I execute a get request to get a list of movies. I'm trying to initialize on site load, and only render components after a successful response from the server.
To do this, the store has the isApplicationReady state, which determines whether the application will be rendered or not. isApplicationReady defaults to false and should change to true when loading movies.
The request looks like this:
export const loadFilms = (page) => (dispatch, _getState, api) => {
api.get(`list_movies.json?limit=15&page=${page}`)
.then(({data}) => {
dispatch(ActionCreator.loadFilms(data.data.movies));
})
.catch((err) => {
alert(`Что-то пошло не так: ` + err);
throw err;
})
}
export const init = () => (dispatch) => {
Promise.all([
dispatch(loadFilms()),
])
.then(() => {
dispatch(ActionCreator.enableApplication(true));
})
.catch((err) => {
dispatch(ActionCreator.enableApplication(false));
alert(`Что-то пошло не так2: ` + err);
throw err;
})
}
dispatch(loadFilms())
in Promise.all, it sends a request to the server, but does not wait for a response and immediately goes to the .then () block, isApplicationReady changes to true, the components are rendered, but the movies still have not come from the server. false // Первичное состояние isApplicationReady
startRequest // Запрос ушел на сервер
true // Promise.all выполнился, перешел к блоку .then() и поменял isApplicationReady на true
[ ] // Компоненты рендерятся, но текущее значение films в store - пустой массив
// На текущем моменте вылетает ошибка, т.к. фильмы отсутствуют и сайт падает, если убрать все данные, то:
{status: "ok" , ..., ...} // Пришел ответ от сервера
[{...}, {...}, ...] //Данные фильмов в store обновились
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question