I am building a simple application. I am using redux toolkit for state management
It has to query the database to check if user is authenticated.
if yes it sets name,email etc for the user
while it is checking the database I want a loading spinner on the frontend the spinner takes the entire screen and will be shown anytime there a database query. for that reason I want to have a seperate app state that has two values viz loading and error
appSlice
const initialState = {loading : false,error:false,error_msg:null}
export const appSlice = createSlice({
name : 'app',
initialState : {value : initialState},
reducers : {
toggle : (state,action)=>{
state.value.loading = action.payload
}
},
});
userSlice
const initialState = { name: "", email: "", role: "", isAuthenticated: false };
export const authenticateUser = createAsyncThunk(
"user/authenticate",
async () => {
let res = await axiosInstance.get("/user/authenticate");
return res.data;
}
);
export const userSlice = createSlice({
name: "user",
initialState: { value: initialState },
reducers: {},
extraReducers: (builder) => {
builder.addCase(authenticateUser.pending, (state, action) => {
//change loading to true for app slice something like (state.app.loading = true)
});
builder.addCase(authenticateUser.fulfilled, (state, action) => {
state.value = action.payload
});
builder.addCase(authenticateUser.rejected, (state, action) => {
//change error to true for app slice something like (state.app.error = true)
//change error_msg to action.payload for app slice
//something like (state.app.error_msg = action.payload)
});
},
});