Best way to check state to see if data exist before making new HTTP GET call?

I have a simple app with one HTTP GET call which populates a list of items.
There are 2 components, a ListView and an ItemView.

How do I tackle the fact that everytime I go back and forth to those two page/components, my Vuex action which populates the list of items is triggered?

  <v-layout row wrap>
    <question
      v-for="(question, index) in questions"
      :key="question.url"
      :id="index"
      :question="question">
    </question>
  </v-layout>
</template>

<script>
  import { mapGetters } from 'vuex';
  import Question from '../Question/Question';

  export default {
    name: 'questionsList',
    components: {
      Question,
    },
    computed: {
      ...mapGetters([
        'questions',
      ]),
    },
    created() {
      this.$store.dispatch('requestItems'); // this runs everytime the route is changed towards that page
    },
  };
</script>

What I did is simple conditionals:

created() {
      if (!this.$store.state.questions.length) {
        this.$store.dispatch('requestItems');
      }
},

but it feels “wrong” - wondering if there’s an API for that or some smart way? (except persist to localStorage which is the best way)

What pattern did you go for here?

Came into a situation, where I faced the same problem. What did you du eventually, @gkatsanos ?

Since I have to check against an object, I used this:

const statusSettings = this.$store.getters['status/getSettings']
const validObject = Object.keys(statusSettings).length

I usually check the state in the action and add a forced parameter to force refetching if data was already set.

actions: {
    fetchX (context, {forced}) {
      if(context.state.X && !forced) return

      fetch(...).then((X) => context.commit('setX', X))
    }

You can use also a soft option to always fetch unless state.X && soft.
It can be paired with a cacheTimeout to force a refresh after some time.
Possibilities are endless

1 Like