'useSelector returns undefined - react-redux
I'm using react-redux
.
createSlice
:
import { createSlice } from "@reduxjs/toolkit";
const datatableSlice = createSlice({
name: "datatable",
initialState: {
filters: [],
columns: [],
},
reducers: {
selectedFilters: (state,action) => {
state.filters = action.payload;
},
selectedColumns: (state,action) => {
state.columns = action.payload;
},
},
});
export const {
selectedFilters,
selectedColumns,
} = datatableSlice.actions;
export default datatableSlice.reducer;
my store:
import { configureStore } from "@reduxjs/toolkit";
import datatableSlice from "./datatable";
const store = configureStore({
reducer: {
datatable:datatableSlice,
[apiSlice.reducerPath]: apiSlice.reducer,
},
});
export default store;
now I have a parent component called ProductPage
:
const ProductPage = () => {
const filters = useSelector((state) => state.filters)
useEffect(()=>{
console.log("filters",filters) //always is undefined
},[filters])
I have a child component called Filters
and it used inside ProductPage
component:
const ProductPage = () => {
const filters = useSelector((state) => state.filters)
....
return (
..
<Filters paramFilters={productFilters}/>
)
inside of Filters
component I use dispatch:
const Filters = (params) => {
const dispatch = useDispatch();
const [filters, setFilters] = useState(params.paramFilters);
useEffect(() => {
const initFilters = getLocalStorage(SELECTED_FILTERS);
if (initFilters) {
setFilters(initFilters);
dispatch(selectedFilters(initFilters));
}else{
dispatch(selectedFilters(filters));
}
}, []);
/**
* To show or hide filters selected
* @param {*} column_id id of each row
* @param {*} show !show or row
*/
const handleFilterCheckboxChange = (filter_id, show) => {
const tmpFilts = filters.map((el) =>
el.id === filter_id ? { ...el, show } : el
);
setFilters(tmpFilts);
setLocalStorage(SELECTED_FILTERS, tmpFilts);
dispatch(selectedFilters(tmpFilts));
};
return (....
but useSelector
always is undefined.
Solution 1:[1]
const ProductPage = () => {
const filters = useSelector((state) => state.filters)
useEffect(()=>{
console.log("filters",filters) //always is undefined
},[filters])
replace state.filters
with the name of the reducer i.e., here in your case state.datatable
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Satyam Saurabh |