I am a new React developer, implementing global state in my app. Im using useReducer with Context API to cache form search data, but I feel I'm using the reducer wrong, even if it works. I am preparing payload BEFORE calling dispatchSearchData, instead of doing it directly inside reducer:
import React, { createContext, useReducer, useMemo, useEffect } from "react";
const initialData = {
from: "",
to: "",
date_go: "",
date_back: "",
passengers: "",
};
const dataReducer = (searchData, newData) => {
if (newData === null) {
localStorage.removeItem("currentSearchData");
return initialData;
}
return { ...searchData, ...newData };
};
const localData = JSON.parse(localStorage.getItem("currentSearchData"));
export const SearchDataContext = createContext({});
export const SearchDataProvider = (props) => {
const [searchData, dispatchSearchData] = useReducer(dataReducer, localData || initialData);
const searchDataValue = useMemo(
() => ({
searchData,
setSearchData,
}),
[searchData, setSearchData],
);
useEffect(() => {
localStorage.setItem("currentSearchData", JSON.stringify(searchData));
}, [searchData]);
return <SearchDataContext.Provider value={searchDataValue}>{props.children}</SearchDataContext.Provider>;
};
An example of calling it:
let search = (e) => {
e.preventDefault();
dispatchSearchData(formData);
setServiceData(null);
}