I've been getting this error where I have set the initialState
of redux with a value, but while debugging it shows its value is null. I'm using Redux Dev-tools to check the values.
And also while adding data inside the initialState
it throws an error Uncaught TypeError: Cannot read properties of null (reading 'push')
Here's my code:
Store.js
import { configureStore } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import authReducer from "../feature/auth/auth.js";
const persistConfig = {
key: "root",
storage,
};
const persistedReducer = persistReducer(persistConfig, authReducer);
export const store = configureStore({
reducer: {
auth: persistedReducer, // Use the persisted reducer here
},
});
export const persistor = persistStore(store);
Feature.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
cookies: [{value: 'test'}]
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
setCookies: (state, action) => {
const data = {
value: action.payload.value
}
state.cookies.push(data)
},
removeCookies: (state) => {
state.cookies = [];
}
},
});
export const { setCookies, removeCookies } = authSlice.actions;
export default authSlice.reducer;
And this is how I'm trying to add cookies:
import { useDispatch } from "react-redux";
import { setCookies } from "../feature/auth/auth";
function About() {
const dispatch = useDispatch()
const handleCookies = () => {
dispatch(setCookies({value: 'test'}))
}
return (
<div>
<h1>About</h1>
<p>This is the about page</p>
<button onClick={handleCookies}>Add Cookeis</button>
</div>
)
}
export default About;
It appears that cookies is null due to your local storage having
{cookies: null}
. Possibly from code earlier in development?https://blog.logrocket.com/persist-state-redux-persist-redux-toolkit-react/
A possible solution would be to delete your local storage, allowing for the cookies value to properly initialize as an array, instead of null. This would also prevent the
Uncaught TypeError: Cannot read properties of null (reading 'push')
from being thrown since it would no longer be calling.push()
onnull