qweezz
qweezz

Reputation: 804

How to prevent Vue make API call on back button click and instead take data from Vuex?

I'm newbie to Vue 3. I trying to do my first app with Vue 3 + Vuex + Vue route.

Step-by-step:

  1. On page load --> API call --> received data set to Vuex store.
  2. Render items on a page from store.
  3. When user clicks on item on homepage, then a new page loading with the data from store (no second API call).
  4. Propblem: when user clicks on browser back button then homepage is rendered again but it makes an API call for the items but I do not need them as they're in store.

How to fix that so if browser back button clicked then no second API call for the same data?

Main component

  methods: {
    ...mapActions('characters', ['getCharacters']),
  },

  mounted() {
    this.getCharacters();
  },

Store action which makes the request:

actions: {
    async getCharacters({ state, commit }, page = state.currentPage) {
      try {
        const res = await fetch(`${BASE_URL}character/?page=${page}`);

        if (res.ok) {
          const { info, results } = await res.json();
          commit('setCharacters', { list: results });
        }
      } catch (e) {
        console.log(e);
      }
    },
};

Upvotes: 0

Views: 860

Answers (1)

Paul Tsai
Paul Tsai

Reputation: 1009

You can check if characters data exists before invoke getCharacters()

computed: {
  ...mapState('characters', ['characters']),
},

methods: {
  ...mapActions('characters', ['getCharacters']),
},

mounted() {
  if (!this.characters) {
     this.getCharacters();
  }
},

Upvotes: 1

Related Questions