we are written new action and a new reducer,
new reducer will update the existing state (product state)
how to call new reducer when a new action is dispatched and old reducer for old action, but both reducers has to update the same state
If old reducer and action is ok, you shouldn't worry about them. Please create your own action with different type and provide own reducer, based on original one (I mean you can't override function as class, so my proposal is to copy-paste existing one from source code), with your new case which supports that action.
StoreModule.forFeature(XXX_FEATURE, yourReducerToken)
Related
In my React Native app I have a generic settings screen that presents users with a question, and a list of options. The question and options are passed to the screen as navigation params (I am using react-navigation v5 and the useNavigation and useRoute hooks).
I want this settings screen to update my redux state when the user clicks on an option. However, the action to be dispatched should be dynamic based on the question being asked. I have a series of actions generated via Redux Toolkit's createSlice. I have exported these actions like so:
export const { changeColorScheme, changeDefaultUnits } = slice.actions;
I initially tried to pass these actions as navigation params to the settings screen, but got the "Non-serializable values were found in the navigation state" warning.
I have since tried to pass the action name as a navigation prop, and in the settings screen I tried dispatching the action with
const dispatch = useDispatch();
const route = useRoute();
[...]
dispatch({
type: route.params.actionName, // eg "changeColorScheme"
payload: theOptionTheUserSelected // eg "dark"
})
This latter method does not seem to trigger the action/reducer at all. I wonder if there's something to do with how Redux Toolkit creates and exports actions that means they cannot be dispatched in this manner?
Am I missing something? Is there another way to potentially achieve the same outcome?
Based on that warning, I assume that React-Navigation's "navigation state" is actually kept in the Redux store. You should not put non-serializable values like functions into the store state, so RTK warns about that.
For the dispatch issue, this is an excellent time to use the Redux DevTools to review what actions are being dispatched, including what the specific action type strings are.
Note that action types generated by createSlice are strings that have two parts, based on the slice name and the reducer name. So, instead of "changeColorScheme", it probably needs to be something like "settings/changeColorScheme". Be sure to use the value from the action creator's type field, like changeColorScheme.type, to have the right value here.
I'm using React Native to build an offline app, and, because I need to pass many data between screens, I decided to use redux. However, I have a doubt concerning the dispatch method. The dispatch method is synchronous right? So what happens when I have code after that dispatch, which depends on the changes that the dispatch made? For example, I have this function:
make_action(){
this.props.dispatch(action());
//rest of the code
}
How can I make sure that the "rest of the code" only runs after the dispatch is completed? Thank you all!!
The short answer is if you want to follow Redux, don't actually put that logic there, where you are indicating with the "rest of the code" comment.
Instead you would use a reducer to handle the result of the action and translate it into a (store) state change. Then you would use the state to drive the impacted view (e.g. container or component), which may be as simple as using that state in its existing render method (if class) or function body (if pure function). Think about the code you are labeling as "rest of the code" and whether it should live in the action itself, state processing (reducer), or the rendered view(s). Typically in a React+Redux app such code as you are proposing would live in one or more of those places, or perhaps it isn't needed at all.
If instead you introduce code where you have the "rest of the code" comment that actually depends on the action having being completed at that point, you are effectively working around (or against) Redux.
Remember that with Redux actions should only return results that are interpreted by reducers to mutate state, which drives views. It's intended to be a unidirectional, cyclical flow of data:
view dispatches action ->
action does something to produce result ->
result is reduced to mutated state, driving updated view ->
... (now we're back to view; repeat)
I want to set data variable globally and I have to update from any page (some of us saying redux can anyone please explain with simple program ?)
See with redux , varibales stored globally are called state, and it sits at the root level. Suppose you create a state object in a reducer :
const INITIAL_STATE = {
phoneNum: '',
}
and when you dispatch actions from your component, you can actually change its value by like dispatch({type:'CHange phone',value:7973913});
And you can dispatch from any any component, and it will trigger the change of phoneNum and even you can access anywhere like suppose this.state.loginReducer.phoneNum
You can check this link react redux for detailed info which are portrayed beautifully.
Hope it help.s
I had implemented redux in my react-native application, on button click I had dispatched method in mapDispatchToProps and called API in action method directly and updated the store in the reducer with API response and retrieved the data from the redux store in mapStateToProps. it works fine.
We can retrieve the data from the redux store in any of our class it works, But Can we update or delete store value in redux directly from our class without dispatching actions in mapDispatchToProps.
Is it possible to manipulate and update store data directly in our class or functions?
No. The only way you can cause state updates in a Redux app is to dispatch actions to the store.
Yes, it is possible. For that you have to import store in your class like this.
import store from ./Filename
//Subscribe your store to get state
store.subscribe(() => console.log(store.getState()))
//dispatch any action from store like following
store.dispatch({ type: 'INCREMENT' })
Given the pattern follows the reducer state remaining immutable dispatch is the layer intended to guarentee the state would only be replaced in that pattern. Remember the function always returns state if using that state to render changes I don't think going around it will give the intended results. There could also be asynchronous calls which may return stale data if dispatch isn't used. I would think the reducer is simply a function so yes it could probably be changed somehow but odd behavior may happen.
We can directly access and modify store object in the following way
import store from './store'
store.dispatch({ payload: JSON.parse(access), type: SET_AUTHENTICATION })
I'm new to React, React Native and Redux so I'm trying to wrap my head around alot of these news concepts for the past few days.
One problem I ran into right now is computing new data in Action Creator, before wrapping it around action object and passing into reducer, that requires a piece of data from other branch within the state tree. How would you normally go about solving this? Changing the structure of the global state tree or map this piece of data to the component requiring it?
Given the state tree:
{
ListView:{
dataSource : a ListView.DataSource type
}
SubmitForm:{
title : 'name of title',
text : 'description'
}
isFetchingData: true/false
}
And supposedly, each branch is handled by a different reducer, and each branch's data is passed into separate component as props.
Here's the scenario (I'm translating the React tutorial to React Native using Redux ):
Submit button is clicked in the SubmitForm
--> dispatch an action to notify store that data is being sent, then async grab and send {title,text} to API server.
Upon success ---> compute the dataSource returned from API server and pass the result dataSource to reducer (according to the tutorial). And by computing dataSource, I mean dataSource.cloneWithRows(....) (explained here), which requires the dataSource from ListView as seen above.
So my thought was the Form component should not have a prop called dataSource, as this is from another branch in the state tree. But without it, I'm not sure how to achieve the desired dataSource. Changing (merging ListView and SubmitForm in this case) the structure of the state tree would also be strange, as to my understanding about Redux pattern. So could someone help me figure this out? Thanks
Thanks guys. I think I found the best solution by using redux-thunk (well I was actually using redux-thunk to handle async action, but didnt read up the api well enough). Basically the thunk is also injected with getState, so basically calling getState() will gain me access to the global state tree and that should solve my problem.
const actionCreator = (args) => {
return (dispatch,getState) => {
// dispatch action to notify store that data is being sent
fetch(url)
.then((response) => response.json())
.then((resData) => {
// dispatch action to notify data received
// compute new data using resData and current dataSource accessed by getState().ListView.dataSource
})
}
}
I have thought this problem before and I think this may be a way.
For example.
You have actionA,reducerA and branchA of store.
You have actionB,reducerB and branchB of store.
Now you want to read branchA and branchB at the same time and change them.
Ok,let us define two actions.
One in actionA(sub-actionA), which to change the branchA.
Another in actionB(sub-actionB), which to change the branchB.
And then, define a total action(total-action),which will call sub-actionA and sub-actionB in order.
The last problem is "How to read branchB in the sub-actionA".
ok, we can use the method 'getState' of store.
We import the store into the actionA, and call
store.getState()
It will return the whole tree of store.
This is a common question, and conveniently has an answer over in the Redux FAQ.
Short version: combineReducers solves a simple use case of splitting reducer functionality by domain/slice-of-state. You've gone past that, and now need to either add custom additional top-level reducer logic to handle this action, or include the additional needed data in the action itself.