javascriptreactjsreduxredux-toolkit

How to reset Redux Store using Redux-Toolkit


I am trying to reset current state to initial state. But all my attempts were unsuccessful. How can I do it using redux-toolkit?

const slice = createSlice({
  name: 'tweets',
  initialState: {
    byTweetId: {},
    byUserId: {},
    allTweetIds: [],
  },
  // reducers
  reducers: {
    // reset: (state) => Object.assign(state, initialState),
    tweetStoreReseted: (state) => {
      //here I need to reset state of current slice
    },
  },
});

Solution

  • Create a initial state separately and use that when you reset

    const initialState = () => ({
        byTweetId: {},
        byUserId: {},
        allTweetIds: [],
    });
    
    const slice = createSlice({
        name: 'tweets',
        initialState: initialState(),
        reducers: {
            resetTweetStore: state => initialState()
        }
    });