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

Discover how to capture a clicked word within the Ionic Framework

I've been working on an app using the Ionic Framework. I am trying to figure out how to detect when a word is pressed in my application. One solution I tried involved splitting the string into words and generating a span with a click event for each on ...

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

Encountering the error message "require is not defined" in the browser while utilizing gulp-browserify for my React.js modules

I am currently working on using gulp-browserify for creating a bundle.js file that will be utilized in the client's browser to initiate rendering of React components. Below is my App.js file: /** @jsx React.DOM */ var React = require('react&apo ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Selenium's WebDriver getAttribute function can return an object of type "object",

In my selenium script, I aim to extract text from table columns following the cell with the specified value. Although the script functions, I encounter an issue where getText() returns [Object Object] in my node.js console. I have attempted various method ...

Looking for a way to extract Regular Expressions from an IgGrid cell in Infragistics?

Is it possible to apply a regular expression to a igTextEditor within an igGrid Updating? I attempted to utilize the validate option, but it was unsuccessful. $("#schedulerTable").igGrid({ columns: $scope.schedulerColumns, widt ...

C# web service is unable to return a specific value

I attempted to use a basic web service (just to test if the value will populate in the JavaScript code). I experimented with a very simple snippet, but it kept returning 'undefined'. Can you offer some guidance? I have tried several solutions wit ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

Tips for avoiding backslashes when creating a JSON file using PySpark

I am trying to format data into a JSON file using PySpark. Here is the desired format: { "list-item": [ {"author":"author1","title":"title1","pages":1,"email":"<a href="/cd ...

Forward to a task with a unique identifier obtained through asynchronous JavaScript calls

I am currently working on an application that utilizes AJAX with FullCalendar functionality. My goal is to enable users to click on a specific item on the calendar, prompting a dialog box with a "View Details" button. Clicking on this button should redire ...

Dynamically parallelizing functions with async and arrays

I have recently integrated the fantastic "async" module by caolan into my Node.js project: Below is a snippet of the code in question: exports.manageComments = function(req, res) { var toDeleteIds = []; var deleteFunctions = []; if (req.body. ...

The process of integrating Tailwind elements into NextJs version 13

Can anyone help me integrate Tailwind elements into my NextJs project using JavaScript instead of TypeScript? I tried following the documentation, but the navbar component's expand button doesn't work. It seems like all components are having some ...

Executing a sequence of jQuery's $.when().then() functions

I am facing challenges in understanding how to properly sequence my functions, especially in relation to the $.when() method. function y() { defer = $.Deferred(); $.when(defer).then(console.log(defer.state())); } y(); <script src="https://ajax.go ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Webpack is failing to recognize certain CSS files

My development stack includes Vue.js 2.5.15, Webpack 4.12.0, css-loader 0.28.11, ASP.Net Core 2.1 in Visual Studio 2017. Starting with the Visual Studio asp.net core template project for Vue and Typescript, I prefer to have individual small CSS files with ...

Optimizing with react and mobX: What You Need to Know

I am new to React and MobX and have been studying various tutorials on using both together. Currently, I am working on creating a form where users can select a product through autocomplete functionality using react-select. Once a product is selected, the i ...

Error: Definitions missing during conversion from JSON to XML

I've scoured the internet extensively, but I still can't figure out why... The header file Newtonsoft.Json.Jsonconvert is missing the definition for DeserializeXmlNode(), which I need to convert Json to Xml. Additionally, the load() function do ...