Show the contents of a JSON file using Vue

I have a JSON file containing some data that needs to be fetched and displayed in a component.

In the actions of my Vuex store, I've implemented:

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 the state looks like this:

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

Now, how can I access these todos from the state and display them when the Homepage is mounted?

An example of the JSON file content:

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

Answer №1

If you want to access state in your components, you can utilize mapState method.

<template>
   <div>
      <div>{{todos}}</div>
   </div>
</template>
<script>
import { mapState } from 'vuex';
export default {
   computed: {
      ...mapState(["todos"])
   }
}
</script>

Answer №2

If you want to retrieve all todos, you can create a getter function like this:

getAllTodos: (state) => state.todos

After that, you need to map the getters in the template :

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Using pdfkit to create a PDF and then returning it as a base64 string from a function

I am attempting to utilize PDFKit to produce a PDF file and then retrieve it as a base64 string. Here is the code snippet I am using: function generatePDFDocument(data){ let doc = new PDFDocument(); var bufferChunks = []; doc.on('readabl ...

Having trouble generating an HTML table from JSON data using JavaScript

My attempt to generate a table with data from an external .JSON file using JavaScript is not working as expected. Everything worked fine when the data was hardcoded into the .JS file, but once I tried to fetch it externally using "fetch", the details do no ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

What is the best way to interpret a JSON with nested structure?

I can't seem to find any errors in the code below, but I keep receiving an error message stating "item._highlightResult.map is not a function". {items.map((item, index) => ( <li key={index}><a href={item.story_url} target="_blank& ...

Load data from a JSON flat file and dynamically populate new <li> elements with it

I'm attempting to utilize data from a json flat file in order to: Create new list items Fill specific classes within the newly created list items The json data appears as follows: { "event": { "title": "Title of event", "preface": "Prefa ...

Clear the cache of a query in React Query without having to fetch it again

Within my React app, I have implemented React Query in the following manner: const { data, status } = useQuery(key, queryFunc, { staleTime: 1 * 60 * 1000 }); In order to invalidate a specific key in the cache based on the value of the data, specifical ...

Utilizing Firebase push notifications with multiple google-service.json files within a single Android Studio project

In a scenario where we have a single project but require multiple Firebase push notification and google-server.json files, how can we effectively manage these multiple files within Android Studio? ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

Implementation of the I18next library

I am currently integrating react-i18next into my application to implement a switch button for French and English languages. Unfortunately, I am facing some issues as the translation is not working properly. I suspect it's related to the JSON file reco ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...

Creating an AJAX request in Knockout.js

Forgive me if this question has been asked previously, as my search attempts have been unsuccessful in finding a solution. Despite consulting the knockout documentation, I still struggle to articulate my issue effectively for searching. My situation invol ...

When clicked, you will be redirected to the details page

Currently, I am developing a React JS application that showcases a list of companies fetched from a Node.js/Express server in a table format. When clicking on each row, it triggers a modal to display some details about the company. The modal consists of t ...

JavaScript for switching between grid layouts

I have organized 3 DIVs using a grid layout. There is a Navigation bar with an on-click event attached to it. When a button on the nav-bar is clicked, I want the JavaScript function to display the corresponding grid associated with that button. Currently, ...

What is the significance of utilizing `.value` within a template when working with a function that produces a computed ref?

One of my functions returns a ComputedRef as shown below: // The computed ref function const publishedBooksMessage = () => computed(() => { return books.length > 0 ? 'Yes' : 'No' }) In order to access the value returned by t ...

Maintain consistent spacing after receiving a value

I have a content editable span where you can write whatever you want. For example: Hello, My name is Ari. However, when I try to retrieve the text and alert it using my program, it displays without any line breaks or spacing like this: "Hello,My name is ...

What could be causing the second image to not drop in the proper position in an HTML and JavaScript environment?

I am encountering an issue with a simple drag and drop implementation using images in my code. The first image works fine, but for some reason the second image does not display correctly when dragged inside the div boxes; it appears outside of the box. Can ...

Splitting up JavaScript and HTML within a WordPress environment

I recently came across a discussion on separating PHP code and HTML at this link I find myself in a similar predicament. My current project involves designing a WordPress website with numerous sliders, animated dropdowns, forms, and other components. The ...

Tips for correctly retrieving the current state from a pinia store to use as an argument for an asynchronous function

I am currently facing an issue with a simple counter store in pinia. The counter itself updates and displays correctly on the page, however, when trying to use the count in a specific function, it does not reflect the updated state of the counter store. Ho ...