Answer the question
In order to leave comments, you need to log in
Is it normal to dispatch an action from another reducer (redux-toolkit) inside redux-thunk?
In redux-toolkit I have 2 modules - auth and profile.
auth => handles information about login, registration, token, etc.
profile => handles information about the user's account
When a user tries to log in, I send a request to the api, which returns me a token and account information. And then I need to save it.
I put the token in the appropriate field (in the same 'auth' module). And I need to put my account information in the 'profile' module. For now, I just dispatch the setProfile action from the auth module.
Is this dispatch of actions between modules an anti-pattern?
Or is it better to move this logic from redux to component?
Or implement the login action outside the modules, and dispatch the actions in the modules at the root of the reducer and from it.
Or do I need to keep it all in one module?
// PROFILE SLICE | profile.js
const initialState = {
data: {},
status: 'idle'
}
export const profileSlice = createSlice({
name: 'profile',
initialState,
reducers: {
setProfile(s, {payload: profile}) {
s.profile = profile
}
}
})
export const {setProfile} = userSlice.actions;
export default profileSlice.reducer
// AUTH SLICE | auth.js
import {setProfile} from './profile' // import action creator from profile slice
const initialState = {
token: null,
status: 'idle'
}
export const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
setToken(s, {payload: token}) {
s.token = token
}
}
})
export const login = ({email, password}) => dispatch => {
return api.auth.login({
email,
password
})
.then(res => {
const {token, ...profile} = res.data
dispatch(setToken(token))
dispatch(setProfile(profile)
})
}
export const {setToken} = authSlice.actions;
export default authSlice.reducer
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question