score:0
you can initialize your state with a value
const [domainlistgroupitems, setdomainlistgroupitems] = usestate(json.parse(localstorage.getitem('leftgroup')));
and then, in your useeffect
, just checking if domainlistgroupitems
is null or not
useeffect(() => {
if (domainlistgroupitems) return; // already set from localstorage
apiservice(leftgroups).then((response) => { .... })
}, [domainlistgroupitems]);
score:0
to limit useeffect to fire only once, you can remove the loadedg from depedency array, now it will simply check if data is already there in local storage or not, if not, it will fetch the data and it will set the data in local storage.
link for article regarding useeffect and dependency array
hope it solves your problem.
score:0
so you want to use localstorage as client cache, it's more interesting to set a date for expiry than to check for existence of the key. in the code snippet below i shimmed localstorage
as ls
and the api call as a promise
with settimeout
for testing purposes.
i extracted the apicall effect as standalone, so you can use it anywhere, and gave it a skip
parameter. in the snippet, the call will be skipped if the localstorage cache dates from less than 7 days ago. you can edit the snippet and uncomment the 2 lines to test what happens when the cache is recent. be sure to expand the snippet to "full page" else the console logs hide the localstorage value :)
const usestate = react.usestate,
useeffect = react.useeffect;
// network call shim
function apiservice() {
return new promise((resolve, reject) => {
settimeout(() => {
try {
resolve({
statuscode: 1,
domaingrouplist: ['hello','world']
});
} catch (err) {
reject(new error('500 server error'));
}
}, 1000);
});
}
// localstorage shim
const ls = object.create({
getitem(key) {
return this[key];
},
setitem(key, value) {
this[key] = value;
}
});
// comment out to see what happens when ls has been populated less than 7d ago
// ls.setitem('lastfetch', new date().toisostring());
// ls.setitem('groupleft', []);
function islessthan7daysago(date) {
const today = new date();
return date > new date(today.setdate(today.getdate()-7));
}
const apicalleffect = (onload, skip) => () => {
if (skip) return;
apiservice().then((response) => {
if (response.statuscode === 1) {
const items = response.domaingrouplist;
ls.setitem('leftgroup', json.stringify(items));
ls.setitem('lastfetch', new date().toisostring());
if (onload)
onload(items);
}
})
.catch((error) => {
console.log(error.message)
});
}
const app = ({
initialitems,
onload
}) => {
const skip = ls.getitem('lastfetch') && islessthan7daysago(new date(ls.getitem('lastfetch')));
const [loaded, setloaded] = usestate(skip);
const [groupitems, setgroupitems] = usestate(initialitems);
console.log(skip ? 'skipping fetch, getting from ls' : 'doing fetch, storing in ls');
useeffect(apicalleffect((items) => {
setloaded(true);
setgroupitems(items);
}, skip), [groupitems]);
return <div>
{ loaded ? <ul>{groupitems.map(x => (<li>{x}</li>)) }</ul> : <div>loading...</div> }
<strong>in localstorage</strong><br/>
<pre>{json.stringify(ls, null, 2)}</pre>
</div>;
};
const storeddomainlistgroupitems = ls.getitem('leftgroup') || [];
reactdom.render(<app initialitems={storeddomainlistgroupitems}/>, document.getelementbyid('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<strong>in app:</strong>
<div id="app"></div>
Source: stackoverflow.com
Related Query
- React: How to hit API only once using useEffect
- React useEffect calls API too many time, How can I limit the API call to only once when my component renders?
- How to call loading function with React useEffect only once
- ReactJS: how to call useEffect hook only once to fetch API data
- How to use react hook useEffect only once in my case?
- How to trigger useEffect in React only once AFTER some certain variable gets loaded
- How do I fire React useEffect hook only once after state change?
- How to get data from an API only once when the page is loaded using axios.get method?
- How to run React useEffect only once and property update state with setState
- How to make only one API request when using React SSR?
- How to call API only once with React Query?
- How to register only once in react useEffect and get useState changes
- How can I ensure that a line of code is executed only once using React hooks in a functional component?
- React API call in useEffect runs only when parameter is hardcoded, not when using state
- How to fix missing dependency warning when using useEffect React Hook
- How do I window removeEventListener using React useEffect
- How to clean up setInterval in useEffect using react hooks
- How to Cache API data using AsyncStorage React Native
- how to update multiple state at once using react hook react.js
- Using React Router and Webpack 2 how to require external libraries only on certain routes?
- How to load the google maps api <script> in my react app only when it is required?
- How to set multiple values at once in react hook form using Typescript
- How to test API calls in react using jest and enzyme?
- How to make a React component fade in on scroll using IntersectionObserver, but only once?
- How to execute store.unsubscribe from useEffect using React hooks and Redux
- How to render React components only once on startup?
- How to ensure a constant inside a component is only calculated once on start in React (Native) with hooks?
- How to make the API call and display it in React JS using React Table and Axios?
- using useEffect in combination with Axios fetching API data returns null - how to deal with this?
- How to set timeout in Fetch API using react js
More Query from same tag
- React JS: ability to detect switching tab in browser
- React Conditional Rendering
- ReactJS: Why shouldn't I mutate nested state?
- React: recursively render nested elements
- Unable to affect child elements with css
- Prop `aria-activedescendant` did not match. react-select
- React state clearing onChange
- Textarea self closing tag? <textarea />
- How can i setState for color change
- Material UI multiple Select MenuItem ref error
- It say missing dependencies in package json
- How to wait until a value is defined until passing it down as a prop in a component
- Use localStorage.getItem() with typescript
- Reactjs not updating dom classes after splicing state
- Material-UI DropZone "getFileAddedMessage" handler returning multiple file names in a single string
- React - My user interface does not re-render properly when my React hook is updated
- React expose component function
- how to simplify the length of the state in react js
- Material UI: Parsing error: Identifier 'Switch' has already been declared
- React: Warning: Each child in a list should have a unique "key" prop
- CORS error even with cors nom package installed
- Remove active state when clicking another div
- React Table Multiple Div
- Access to items of a generated list
- how to store date in the firebase with type 'timestamp' instead of 'map' from reactjs
- How to increment the filename if file already exists in javascript
- errorr in node:internal/modules/cjs/loader:488
- multiple sessions established to socket io
- Filtering API data and rendering items upon a button click
- highlight active page link in React/Gatsby