I've used useReducer hook in react. al of my code seems right but it isn't working. Here goes my code
import React, { useEffect, useReducer, useContext } from 'react';
import reducer from '../reducers/filter_reducer';
import { useProductsContext } from './products_context';
import { LOAD_PRODUCTS } from '../actions';
const FilterContext = React.createContext();
const initialState = {
filtered_products: [],
};
const FilterProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const { listOfProducts } = useProductsContext();
useEffect(() => {
dispatch({ type: LOAD_PRODUCTS, payload: listOfProducts });
}, [listOfProducts]);
return (
<FilterContext.Provider value={{ ...state }}>
{children}
</FilterContext.Provider>
);
};
export const useFilterContext = () => {
return useContext(FilterContext);
};
export default FilterProvider;
and there goes my reducer function :
import { LOAD_PRODUCTS } from '../actions';
const filter_reducer = ({ state, action }) => {
if (action.type === LOAD_PRODUCTS) {
return { ...state, filtered_products: action.payload };
}
};
export default filter_reducer;
It seems my code is right but after running this code it shows this error:
TypeError: Cannot read property 'type' of undefined
Can someone see where I'm wrong?