I am using redux in a project, the issue is that am saving a token gotten from login of a user, but when i try to use it a component it returns null.
i used console.log to verify that it saving in the redux store but when using consolelog to check if am extracting it correctly it returns null.
this my redux store
import { configureStore } from "@reduxjs/toolkit";
import session_slice from "./slices/session_slice";
import term_slice from "./slices/term_slice";
import login_slice from "./slices/login_slice";
import tenant_slice from "./slices/tenant_slice";
export const store = configureStore({
reducer: {
session: session_slice,
term: term_slice,
login: login_slice,
tenant: tenant_slice,
}
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
this part is where am trying to check it in a component but it returns null
import { useSelector } from 'react-redux';
const Real = () => {
const token = useSelector(state => state.login.token);
// Use the token for operations here
console.log("Token in component:", token);
return <div>My Component</div>;
}
export default Real
this is my loginsplice where i save the user token and data gotten from my api.
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import login from '../../api/admin/login';
export const loginUser = createAsyncThunk('login/loginUser', async ({ email, password }, { rejectWithValue }) => {
try {
const data = await login(email, password);
return data;
} catch (error) {
return rejectWithValue(error.message); // Capture and return the error message
}
});
const loginSlice = createSlice({
name: 'login',
initialState: {
user: null,
token: null, // Add token to initial state
status: 'idle',
error: null
},
reducers: {
logout: (state) => {
state.user = null;
state.token = null; // Clear the token on logout
}
},
extraReducers: (builder) => {
builder
.addCase(loginUser.pending, (state) => {
state.status = 'loading';
state.error = null; // Clear previous errors
})
.addCase(loginUser.fulfilled, (state, action) => {
state.status = 'succeeded';
state.user = action.payload.data;
console.log(action.payload.data)
state.token = action.payload.data.token; // Store the token
console.log(action.payload.data.token)
state.error = null; // Clear previous errors
})
.addCase(loginUser.rejected, (state, action) => {
state.status = 'failed';
state.error = action.payload; // Capture error message
});
}
});
export const { logout } = loginSlice.actions;
export default loginSlice.reducer;
2
Answers
use local storage to store token
Inspect using react dev tool . find actully what happen to your varible