I want to implement the logic of authorizing users when the page loads. Initially, I wanted to check if there is a token in the cookie (checkUserToken
) and if there is or not - call another function (fetchUserData
) which will make a future request to the server. Finally, when the server responds - the third function (setUserData
) is called which will populate userData
'use client' import { createSlice } from "@reduxjs/toolkit"; import { getCookie } from '@/app/untils/Cookies'; const initialState = { userData: null } export const userSlice = createSlice({ name: "userData", initialState, reducers: { checkUserToken: () => { console.log('chekc') const token = getCookie('user-token'); console.log(token) if (token) return fetchUserData(token) else return fetchUserData(false) }, fetchUserData: async (state, action) => dispatch => { return console.log('FETCH') // console.log(state) // console.log(action) }, setUserData: (state, action) => { console.log('SET USER') console.log(action) console.log(state) } } }) export const { checkUserToken, fetchUserData, setUserData } = userSlice.actions export default userSlice.reducer
How can I implement similar functionality in my slice?
Reducer functions are pure functions, they do not perform side effects like dispatching actions.
checkUserToken
cannot dispatch any actions,fetchUserData
cannot return function values. It seems to me thatcheckUserToken
andfetchUserData
are actually asynchronous actions. Create a thunk action for them.Example:
Please note that the
fetchUserData
action can directly access cookies/tokens, and thefetchUserData.fulfilled
reducer case can also set/update user data status. This means that thesetUserData
andcheckUserToken
actions may be unnecessary.