Reputation: 1159
I have this slice
logout.js
import { createSlice } from '@reduxjs/toolkit';
import { logoutUser } from './actions/logoutUserAction';
const initialState = {
status: null,
};
const logout = createSlice({
name: 'logout',
initialState,
reducers: {
changeStatus: state => { <===== I want to use this action
state.status = null;
},
},
extraReducers: {
[logoutUser.pending]: state => {
state.status = 'loading';
},
[logoutUser.fulfilled]: state => {
state.status = 'success';
},
[logoutUser.rejected]: state => {
state.status = 'failed';
},
},
});
export const { changeStatus } = logout.actions;
export default logout.reducer;
logoutuserAction.js
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import { changeStatus } from '../logout';
export const logoutUser = createAsyncThunk(
'logout/logoutUser',
async (data, { dispatch }) => {
return axios({
method: 'get',
url: '/logout',
withCredentials: true,
}).then(res => {
dispatch(changeStatus()); <=== I use it here
localStorage.removeItem('isAuthenticated');
return res.data;
});
}
);
I was reading about it here https://redux-toolkit.js.org/usage/usage-guide/#exporting-and-using-slices but I didn't understand this part:
If you encounter this, you may need to restructure your code in a way that avoids the circular references. This will usually require extracting shared code to a separate common file that both modules can import and use. In this case, you might define some common action types in a separate file using createAction, import those action creators into each slice file, and handle them using the extraReducers argument.
What I get:
Upvotes: 5
Views: 1488
Reputation: 44136
You should be able to do that by putting logoutUser
in the same file, above the createSlice
call, but... why are you doing that though? A blink of an eye later, logoutUser.fulfilled
is being dispatched and you can do the same stuff just in that extraReducer..?
Upvotes: 1