admin管理员组文章数量:1425156
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
},
},
});
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
},
},
});
Share
Improve this question
asked Jan 9, 2021 at 16:55
John JohnJohn John
1,5004 gold badges23 silver badges45 bronze badges
4 Answers
Reset to default 4Create 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()
}
});
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= [];
},
},
});
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
本文标签: javascriptHow to reset Redux Store using ReduxToolkitStack Overflow
版权声明:本文标题:javascript - How to reset Redux Store using Redux-Toolkit - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745442087a2658490.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论