0

I've json file with some data. I've to fetch this data and display them in the component.

In my vuex store in actions I have:

async getTodos (context) {
  const todos = []

  const response = await fetch('../../data/todos.json')
  const responseData = await response.json()

  todos.push(responseData)

  context.commit('getTodos', todos)
}

mutations:

getTodos (state, payload) {
  state.todos = payload
}

and state:

state () {
  return {
    todos: []
  }
}

And now how to get this todos in state and display them when Homepage is mounted?

JSON file example:

[
  {
    "id": "1",
    "title": "1st todo",
    "description": "First task",
    "dueTo": "2021-10-03"
  },
  {
    "id": "2",
    "title": "2nd todo",
    "description": "Second task",
    "dueTo": "2021-10-02"
  }
]

2 Answers 2

3

Well you can use mapState in your components

<template>
   <div>
      <div>{{todos}}</div>
   </div>
</template>
<script>
import { mapState } from 'vuex';
export default {
   computed: {
      ...mapState(["todos"])
   }
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

You can make getter for todos:

getAllTodos: (state) => state.todos

Then map getters in template :

import { mapGetters } from 'vuex';
computed: {
  ...mapGetters([ 'getAllTodos' ]),
},

<template>
  <ul>
    <li v-for="(todo, i) in getAllTodos" :key="i">{{todo}}</li>
  </div>
</template>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.