Issue
I have a React app that has multiple tabs. When the user goes to the "Data" tab it will fetch data from an API call and set the data in a React state. However, if the user goes from "Data" tab to "Home" tab then back to "Data" tab it will have to fetch the data again from API call because data in state has disappeared.
Psuedocode of desired functionality:
const OutputTab: React.FC<PageProps> = ({ match, pageName }) => {
const [outputData, setOutputData] = useState<outputsInterface[]>([]);
useIonViewWillEnter(() => {
if (!outputData) {
fetchOutputs();
}
});
const fetchOutputs = () => {
let response = fetch("....");
setOutputData(response.json);
};
};
What is the simplest way to store the state data? Desired functionality is when user comes back to the tab we can simply check if data already exists rather than making another API call to refetch.
I thought of possible solutions to use localStorage
or sessionStorage
but I'd prefer to store the data in memory rather than storage. Do I need something like Redux to accomplish this?
Solution
full solution with video examples here with source code in codesandbox
- https://youtu.be/DiCzp5kIcP4
- https://dev.to/aaronksaunders/two-ways-to-manage-state-in-react-js-5dkb
Using Context API
import React from "react";
// create the context
export const Context = React.createContext();
// create the context provider, we are using use state to ensure that
// we get reactive values from the context...
export const TheProvider = ({ children }) => {
// the reactive values
const [sharedValue, setSharedValue] = React.useState({
value: "initial",
changedBy: "Admin"
});
// the store object
let state = {
sharedValue,
setSharedValue
};
// wrap the application in the provider with the initialized context
return <Context.Provider value={state}>{children}</Context.Provider>;
};
export default Context;
Using Reducer with useReducer
const reducer = (state: IState, action: ActionType): IState => {
switch (action.type) {
case "update":
return { ...state, ...action.payload };
case "clear":
return { ...state, ...action.payload, value: "" };
default:
throw new Error();
}
};
const [state, dispatch] = React.useReducer(reducer, initialState);
Answered By - Aaron Saunders
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.