How to reset Redux Store using Redux-Toolkit

Viewed 1310

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
    },
  },
});
3 Answers

Create a initial state separately and use that when you reset

const initialState = () => ({
    byTweetId: {},
    byUserId: {},
    allTweetIds: [],
});

const slice = createSlice({
    name: 'tweets',
    initialState: initialState(),
    reducers: {
        tweetStoreReseted: state => initialState()
    }
});

This should suffice

const slice = createSlice({
  name: 'tweets',
  initialState: initialState,
  reducers: {
     tweetStoreReseted: () => initialState()
  }
});

I tried many solutions I found on the web but none worked after trying it out. This is what I eventually found that worked:

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