How an Action update multiple different Reducers? How can i implement like this?
UPDATE:
this is my action in ./actions/sync.js. this action connected to an external API and call from Sync Component, periodically.
export function syncFetch(response) {
return {
type: 'SYNC_FETCH',
response
}
}
export function syncFetchData(url) {
return (dispatch) => {
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
.then((sync) => updateAll(sync))
.catch(() => console.log('error'));
};
}
const updateAll = (params) => {
return dispatch => {
dispatch({type: 'SYNC_FETCH', payload: params})
}
}
and ./reducers/sync.js
const initialState = [];
export default (state = initialState, action) => {
switch(action.type) {
case 'SYNC_FETCH':
return action.response;
default:
return state;
}
}
i got not error, but data not update. what is problem in my code?
Having multiple reducers become an issue later when we create the store for our redux. To manage the multiple reducers we have function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them.
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
It turns out that Redux lets us combine multiple reducers into one that can be passed into createStore by using a helper function named combineReducers . The way we combine reducers is simple, we create one file per reducer in the reducers directory. We also create a file called index. js inside the reducers directory.
Reducers: As we already know, actions only tell what to do, but they don't tell how to do, so reducers are the pure functions that take the current state and action and return the new state and tell the store how to do.
From react-redux 7.1
, you can leverage the batch
API to dispatch all the actions on a single re-render. From the docs you can do something like:
import { batch } from 'react-redux'
function myThunk() {
return (dispatch, getState) => {
// should only result in one combined re-render, not two
batch(() => {
dispatch(newsAction(newsParam))
dispatch(userAction(newsParam))
dispatch(notifyAction(newsParam))
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With