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>


Related Query

More Query from same tag