js and @reduxjs/toolkit in my project. When I try to get data from store with useSelector method, undefined value returns.
here my reducer file:
import { createSlice } from "@reduxjs/toolkit";
export const deviceSlice = createSlice({
name: "isMobile",
initialState: {
value: false,
},
reducers: {
detectDevice: (state) => {
state.value = !state.value;
},
},
});
export const { detectDevice } = deviceSlice.actions;
export default deviceSlice.reducer;
here my store.js file :
import { configureStore } from "@reduxjs/toolkit";
import { detectDevice } from "./device";
export default configureStore({
reducer: {
isMobile: detectDevice,
},
});
and my index.js file :
import Head from "next/head";
import Nav from "../components/nav/Nav";
import { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { detectDevice } from "../redux/device";
export default function Home() {
const dispatchDetectDevice = useDispatch();
let size = useSelector((state) => state.isMobile.value);
useEffect(() => {
if (window.innerWidth < 576) dispatchDetectDevice(detectDevice(true));
else {
dispatchDetectDevice(detectDevice(false));
}
console.log(size);
});
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Nav />
</div>
);
}
The console.log() method on line 15 returns undefined value.
What do you think is the reason for this?
Your global state cannot be accessed unless your application has been wrapped with the Redux store's provider. This could explain why your size is undefined.
I don't see any issues on your store.js nor device.js files.
Could you please enclose your _app.js file?
This should be in it:
import { Provider } from "react-redux";
import store from "PATH_TO_YOUR_STORE";
function MyApp({ Component, pageProps }) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
export default MyApp;