Search code examples
vue.jsaxiossession-storage

Vue + Axios with sessionStorage


Goal: Initially load posts using the Wordpress Rest API via Axios once in a Vue View, and only once during a session of visiting the Vue website.

Current Result: I currently fetch the results successfully and set them in sessionStorage. They display correctly. I want to know/learn if I am accomplishing this correctly and have the process optimized in the best way possible. I've looked up documentation and I think I have it down.

Current Code:

<script>
import Hero from "@/components/Hero.vue";
import axios from "axios";

export default {
  name: "About",
  components: {
    Hero,
  },
  data: function() {
    return {
      eatery: [],
    };
  },
  created() {
    axios
      .get("//localhost:81/wp-json/wp/v2/posts?_embed&per_page=5&categories=2")
      .then((response) => {
        sessionStorage.setItem("eatery", JSON.stringify(response.data));
      })
      .catch((error) => {
        window.alert(error);
      });
  },
  mounted() {
    if (sessionStorage.getItem("eatery")) {
      this.eatery = JSON.parse(sessionStorage.getItem("eatery"));
    }
  },
};
</script>

Solution

  • I would check whether it's in the storage before trying to load it. In your case, it would look like this:

    export default {
      name: "About",
      components: {
        Hero,
      },
      data: function() {
        return {
          eatery: [],
        };
      },
      loadEatery() {
        axios
          .get("//localhost:81/wp-json/wp/v2/posts?_embed&per_page=5&categories=2")
          .then((response) => {
            sessionStorage.setItem("eatery", JSON.stringify(response.data));
            return response.data;
          })
          .catch((error) => {
            console.error(error); // for debugging maybe
          });
      },
      mounted() {
        if (sessionStorage.getItem("eatery")) {
          this.eatery = JSON.parse(sessionStorage.getItem("eatery"));
        } else {
          loadEatery().then(data => this.eatery = data);
        }
      },
    };