This is how my login action looks like and it works correctly:
export const login = createAsyncThunk(
'auth/login',
async (data, thunkAPI) => {
const response = await API.login(data)
//Store user data in local storage
Storage.save('user', response.data)
// Add token to HTTP headers
API.setToken(response.data.key)
return response.data
})
Now I need to do the logout function but when using "createSlice()" I have no option of adding side effects since it goes straight to the reducer (and Redux documentation says we should not add any side effects to the reducers)
// Slice
const authSlice = createSlice({
name: 'auth',
initialState: {
user: null
},
reducers: {
// Logout
logout: (state, action) => {
state.user = null
},
},
extraReducers: {
[login.fulfilled]: (state, action)=>{
state.user = action.payload
},
}
})
So I thought I could maybe use the createAsyncThunk function to execute the side effects before it hits the reducer:
export const logout = createAsyncThunk(
'auth/logout',
async (thunkAPI) => {
//Remove user data in local storage
Storage.remove('user')
// Remove token to HTTP headers
API.removeToken()
}
)
Is this an appropriate use of "createAsyncThunk"?
Hopefully someone with more experience can help with this.
Many thanks!