Reputation: 1455
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
},
},
});
Upvotes: 3
Views: 3990
Reputation: 1683
Another case sample :
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
username : false,
password : false
}
export const AuthSlice = createSlice({
name: 'login',
initialState,
reducers: {
setUsername: (state, action) => {
state.username = action.payload
},
setPassword: (state, action) => {
state.password = action.payload
},
resetLogin: () => initialState // this part is to reset
}
})
export const { resetLogin, setUsername, setPassword } = AuthSlice.actions
export default AuthSlice.reducer
Upvotes: 0
Reputation: 4470
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()
}
});
Upvotes: 4
Reputation: 1
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= [];
},
},
});
Upvotes: 0
Reputation: 1928
This should suffice
const slice = createSlice({
name: 'tweets',
initialState: initialState,
reducers: {
tweetStoreReseted: () => initialState()
}
});
Upvotes: 0