Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset the state to it's initial state in redux store?

In redux store I have set initial state to some value as shown below:

const search_initial_state = {
FilterItem:18
}

I am changing this state value in another function manually But after click on reset button I want to set "FilterItem" state to it's initial value.(i.e. 18)

like image 870
Nikita Wagh Avatar asked Dec 23 '22 01:12

Nikita Wagh


2 Answers

If i understood you correctly, you want to reset only one value to its original/initial value.

Define an action creator that dispatches action type of RESET_FILTER_ITEM and then whenever you want to reset filter item dispatch this action.

const resetFilterItem = () {
    return {
      type: "RESET_FILTER_ITEM"
    }
}

and your reducer will look like this after implementing reset case

const myReducer = (state = initialState, action) => {
   switch(action.type){
      case "OTHER_CASE":
        return {...state}
      case "RESET_FILTER_ITEM":
        return {
           ...state,
           FilterItem: initialState.FilterItem
        }
      default:
        return state  
   }
}

Hope this will help you.

like image 98
Tushar Korde Avatar answered Dec 31 '22 01:12

Tushar Korde


Reducers will update their state when an action has been dispatched for them to process. So likewise, you have to dispatch an action that tells your reducer to return the initial state.

//Reducer code
const initialState = {}

const myReducer = (state = initialState, action) => {
   switch(action.type){
      case "FILTER_ITEM":
        return {...someUpdatedState}
      case "RESET_ITEM":
        return initialState
      default:
        return state
  }
}

Your reducer will return a new state depending on the action type.

So just define an action creator that dispatches action type of RESET_ITEM or something else you may want to call it. Then use it when you want to reset.

const resetItem = () => {
   return {
      type: "RESET_ITEM"
   }
}
like image 22
Chris Ngo Avatar answered Dec 31 '22 03:12

Chris Ngo