Reputation: 126
In a reducer function we usually return default state if it doesn't go to switch block.
function reducer(state = initialState, action: any): any {
switch (action.type) {
case SOME_TYPE:
return Object.assign({}, state, {
someBoolean: false
});
}
return state;
}
I tried dispatch(undefined, {type: undefined})
but I got error action may not have undefined type.
Is there a way that we could dispatch action which will return defalut state.
PS: Just trying a different way. Of-course we can have some action type and return default state.
Upvotes: 0
Views: 1848
Reputation: 17664
You should use the action's paylaod to update the state, and you can check if you have any payload, use it, otherwise go back to initial state
function reducer(state = initialState, action: any): any {
switch (action.type) {
case SOME_TYPE:
return Object.assign({}, state, {
someBoolean: action.payload.someBoolean || initialState.someBoolean
});
}
return state;
}
And dispatch an undefined
:
dispatch({
type: SOME_TYPE,
payload: {
someBoolean: undefined
}
});
But a better way would be to have a type
to revert back to initialState
function reducer(state = initialState, action: any): any {
switch (action.type) {
case SOME_TYPE:
return Object.assign({}, state, {
someBoolean: false
});
case REVERT:
return initialState;
}
return state;
}
Upvotes: 0
Reputation: 41913
If I have understood you correctly, you want to reset your state to the initial value.
switch (action.type) {
case SOME_TYPE:
return Object.assign({}, state, {
someBoolean: false
});
case 'DEFAULT':
return initialState;
default:
return state;
}
Then simply dispatch it:
dispatch({ type: 'DEFAULT' });
Note: remember to add a default
case inside your reducer.
Upvotes: 1
Reputation: 538
Not sure if I'm getting this correctly, but to return your state simply do:
function reducer(state = initialState, action: any): any {
switch (action.type) {
case SOME_TYPE:
return state;
}
return state;
}
Or to reset your initial state, do:
function reducer(state = initialState, action: any): any {
switch (action.type) {
case SOME_TYPE:
return initialState;
}
return state;
}
Upvotes: 0