Answer the question
In order to leave comments, you need to log in
How to implement a method call in response to a state change in react-redux?
There are two components: an authorization form and a shopping cart. An unauthorized user may have an empty cart, while an authorized user may have goods there. Accordingly, after authorization, it would be good to request a basket using AJAX and update the state if its composition is different.
I use react-redux with "smart" and "stupid" components.
After successful authorization, I pass the result to action and change the user state to user.isAuthorized. Components that follow this property will be rerendered.
But I don’t need the cart to be re-rendered upon authorization, I first need to make an AJAX request, and then render the cart based on its results.
Controller components only have the connect() function with its argument functions that pass data to the view. Such components do not know how to somehow respond to state changes (I'm not mistaken in this, right?).
You can, of course, stupidly subscribe to user.isAuthorized changes, but there are two things that stop me:
1. It is not recommended to use it in guides
2. It will be called for every sneeze, essentially empty, in this case it is better to wrap it in an Observable and build that's all the interactions in the app.
Are there any traditional ways to solve this problem?
Answer the question
In order to leave comments, you need to log in
Good afternoon.
Imagine your action creator (function), which on success returns a successful authorization, for example:
$.ajax(url...
success(data) { dispatch({type: AUTH_SUCCESS, data }) })
$.ajax(url...
success(data) {
dispatch({type: AUTH_SUCCESS, data })
loadUserCart(data.user_id) // <- еще один action creator
})
function loadUserCart(id) {
return (dispatch) => {
dispatch({ type: CART_REQUEST }) // получается, это событие вызовется сразу после успешной авторизации, практически мгновенно
$.ajax(urlForCartUpdate...
success(data) {
dispatch({type: CART_SUCCESS, data })
})
}
}
{
ваше_название_поля: reduxStore.название_редьюсера
}
function mapStateToProps(state) {
return {
rate: state.rate,
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question