How to save data in to cache come from rest API with Axios in Vue 3 with option API

Viewed 28

How to avoid duplicate API requests in Vue 3 with option Api. That means cache the data in the browser when first visited the API

1 Answers

You might want to take a look at localStorage, it allows you to store data in the browser (only strings, but JSON.stringify and JSON.parse are your friend) over multiple sessions. You do have direct access to the window.localStorage-object in every browser environment (not NodeJS), so it can totally be used with front-end frameworks like vue.js.

You can find a very minimal example at Codesandbox:

if (localStorage.getItem("result")) {
  this.result = JSON.stringify(localStorage.getItem("result"));
} else {
  const data = fetch("YOUR_URL").then(async (res) => {
    const json = await res.json();
    localStorage.setItem("result", JSON.stringify(json));
    this.result = json;
  });
}
Related