I have some "ChangeMainItem" Action (in my case it is dispatched by external system or possibly one of components). This action (eg {type:Change_Main_Item, itemId:5}
) updates only one property of state in reducer (eg mainItemId
).
My Component A and B needs to react on this state change: show loading indicator, fetch additional data and show results. Sequential actions can be done via some async action library - but where should I place dispatching async action? Obviously, i can't dispatch async action in reducer of Component A and B, neither i want to change original Action to async so it can make any necessary requests for my components.
What is the right way to achieve this?
I suggest using sagas to listen to your defined actions and manage your async calls/actions from there. Redux-saga is awesome.
import { put, takeEvery } from 'redux-saga/effects'
import {Change_Main_Item, ANOTHER_ACTION, THIRD_ACTION} from '../actions'
function* doSomething() {
yield put({type: "ANOTHER_ACTION", payload: data});
}
function* doAnotherThing() {
yield put({type: "THIRD_ACTION", payload: data});
}
function* mySaga() {
yield takeEvery("Change_Main_Item", [doSomething, doAnotherThing]);
}
Please see https://github.com/redux-saga/redux-saga
Well, you have multiple approaches to such a question.
You can use a redux-thunk so you can dispatch multiple actions and have your state react to all such dispatches. Thunk middleware is useful when you need to perform async actions.
example:
function changeMainItem(id) {
return (dispatch, getState) {
dispatch(requestChangeMainItem); //This tells the state that it's loading some ajax; you presumably want to add some boolean, indicating a loading icon.
return makeSomeRequest(id)
.then(data => {
dispatch(changeMainItem(data.id)) //presumably, this is where you update your item
// perhaps dispatch another function to do more stuff.
})
}
}
You then will need to figure out which components need to be subscribed/connected to certain properties in your state.
Read about async action , redux-thunks , and this article on how to connect your components to your state
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.