How to cache ReactJS fetch json results for a period of time in localStorage
--
In a ReactJS app i was calling an external API to get some news and display to the user. Every time this page was loading i had this external API call.
So i need to make a small 5 minute caching of the result in order to avoid external calls.
In my function i have a function getContent that fetch the result and it is called by an effect.
You need to replace the URL and the results layout with your own data.
import React, { useMemo, useEffect,useState } from "react";export function GoogleNewsWidget() { //loader animation - status
const [loading, setLoading] = useState(false); // our data
const [data, setData] = useState({});async function getContent() {
// set loading true
setLoading(true);
// fetch url
const metadataResponse = await fetch(process.env.REACT_APP_NEWS_URL, {
method: 'GET',
mode: 'cors',
cache: 'default'
});
// get response
const resp = await metadataResponse.json();
if (resp!==null) setData(resp);
//stop the animation
setLoading(false);} useEffect(() => {
getContent();
});return (<>{loading ? <div> Loading ... </div>:(
<div>
<h3>Data</h3>
<ul> {data.map!=undefined?data.map(d => (
<li>{d}</li>
))}
</ul> </div> )
}}
Now .. lets add a caching using local storage
import React, { useMemo, useEffect,useState } from "react";export function GoogleNewsWidget() {//loader animation - status
const [loading, setLoading] = useState(false);// our data
const [data, setData] = useState({});async function getContent() { // set loading true
setLoading(true); // get cached data
let cached_data = localStorage.getItem('cached_data');