Utilizing mapState in Vuex to display data on the view

Trying to fetch data from an API and display it on views using Axios and Vuex for state management. The code below can log the data but is unable to pass it to the view.

Changing from mounted() to changed() did not solve the issue.

Here's the source code: In ‘./store/modules/form.js’ :

import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);

const state = {
  posts: [],
};
const mutations = {
  setPosts(state, posts) {
    state.posts = posts;
  }
};
const actions = {
  loadPosts({ commit }) {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then(response => response.data)
      .then(posts => {
        commit("setPosts", posts);
        console.log(posts);
      });
  }
};
export default {
  //namespaced: true,
  state,
  mutations,
  actions
};

In './store/index.js :

import Vuex from "vuex";
import Vue from "vue";
import form from "./modules/form";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    form
  }

});

In ‘components/Posts.vue’ :

<template>
  <div>
    <div class="container">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Body</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="post in posts" :key="post.id">
            <td>{{ post.id }}</td>
            <td>{{ post.title }}</td>
            <td>{{ post.body }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "PostsPage",
  computed: mapState(["posts"]),
  mounted() {
    this.$store.dispatch("loadPosts");
  },
};
</script>

If you have any insights or solutions, I would greatly appreciate your help. Thank you!

Answer №1

After considering his use of modules, it might be worth suggesting the following:

computed: mapState("form", ["posts"]),

(Unfortunately, my reputation is not high enough to leave a comment :( )

Answer №2

Vue.js is something I'm just starting out with, but one way to render posts in the component you desire is:

import { mapState } from 'vuex';

After that, add this to your computed properties: { ...mapState(['posts']) }

Answer №3

In my applications, I have implemented various methods depending on the specific requirements. Feel free to try one of the following:

...mapState("form", ["posts"])
or
...mapState("form", {
  posts: state => state.posts
})
or
...mapState({
  posts: state => state.form.posts
}),

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

Guide to incorporating JavaScript libraries from NPM into a child theme built on Understrap

I am looking to incorporate the Chart Js library within my custom Understrap Child Theme. Instead of simply using a CDN script, which could potentially slow down load times or cause errors if the CDN is not accessible, I have opted to import it into my pac ...

IE6 does not support Ajax jquery functionality

Currently, I am facing an issue with my ajax jquery code. It seems to be working perfectly on all browsers except for IE6. I have tried making some changes but unfortunately, it did not solve the problem. I would greatly appreciate any help or suggestions ...

Issue with Select2: When using a remote select2 control, the tab key press does not allow for the selection of the highlighted

I have set up select2 to load ajax data into select2 based on the example provided in this link Load ajax data into select2. In the example, I can type text, use arrow keys to navigate, and then hit tab to select the highlighted item. However, in my case, ...

Scaling Images using HTML and CSS

Hey there, I'm currently learning web development and running into a bit of trouble with creating responsive images. Can anyone give me some guidance on what changes I should make in the code below? Here's the HTML code: <div class="caro ...

Finding the median value within a collection of objects

I am working with an array of objects containing book details: const booksData = [{"author":"john","readingTime":12123}, {"author":"romero","readingTime":908}, ...

Error: When attempting to utilize the Image-Slider, an issue arises with reading the property 'classList' which is undefined

I am currently in the process of developing a website using Strapi as my CMS and Next.js(React) for the frontend. The website features an image slider that includes images, headlines, and descriptions. However, I have encountered an issue where after spen ...

Struggling to get SmartWizard Jquery 4 to integrate smoothly with Bootstrap 4

Greetings, StackOverflow community! I am a newcomer here seeking assistance with fixing my code. I am struggling to get SmartWizard jQuery 4 to function properly. Despite meticulously copying every line of code (excluding css and js file sources), the plug ...

Convert Initialization Vector (IV) to hexadecimal format, save it into a file, later read it from the file, then convert the hexadecimal to binary. The process continues with various operations in NodeJS

I am attempting to convert an Initialization Vector into a hexadecimal string, and then reverse the process back to binary. However, when I try to display the output in the console, it is showing the following: fIV: undefinedundefinedundefinedundefinedunde ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

Is it possible to use jQuery's .attr method to change the href attribute if a certain text is contained within a DIV

(Twitter) I'm struggling with how to incorporate the .attr method at the start of links/A/href when the selected element contains specific words: $(".tweet:contains('government','Anonymous')").each(function(){ $old_url = $(thi ...

What could be causing the JavaScript alert to trigger twice?

<script type="text/javascript"> function ChangeStyle() { document.getElementById("p1").innerHTML = "<a href='javascript:void()' onclick=\"window.location.href='http://google.com'\">The New Link</a&g ...

Innovative Features in Google Chrome

There is a nifty effect on Google Chrome that makes tabs light up when new content appears on the page and you are not currently viewing that tab. It can often be seen on sites like grooveshark. If anyone knows how to recreate this effect, I would greatl ...

Creating a primary php file in Apache without the use of SQL or any database: is it possible?

Forgive me if this comes across as rude, but I'm struggling to grasp the concept of apache, PHP, and servers in general. To help myself understand better, I want to create a very basic website that assigns an ephemeral ID to each user (not a session). ...

Using 'if' conditions in Reactjs: A step-by-step guide

Working with Reactjs in the nextjs framework, I have received user data that includes the "category name (cat_name)" selected by the user. Now, I need to display that category in a dropdown menu. How can I achieve this? The current code snippet showcases ...

Elements are failing to render properly within the template tag

Why are the elements not visible within the template tag? <script setup> import { getAuth } from 'firebase/auth' const auth = getAuth() const user = ref(null) watch(() => { if (auth.currentUser) { user.value = auth.currentUser } }) ...

Performing simultaneous read and write operations in node.js and C to a text file

Is it possible for my node.js function to read from a file while a C program is writing to it at the same time? Currently, the node.js function cannot read while the C program is writing, and I would like to remove that lock. Additionally, I need the node ...

Recognizing when console.log() is used

Currently, I'm in the process of creating a test case for a debugging technique that utilizes console.log() to write messages to the JavaScript console. The objective of the test is to verify that the message has indeed been successfully logged to the ...

Choosing based on conditions within a function

I am currently working with an object that contains orders from a restaurant. var obj = { orders: [ null, { date: "2018-07-09 10:07:18", orderVerified : true, item: [ { name ...

Protractor's getText method fails to retrieve the value of an input field

It's important to note that the following code snippet may cause issues: element(by.model('someModel')).sendKeys('some value'); expect(by.model('someModel').getText()).toMatch('some value'); This test case wil ...

Error in Angular $injector: Unknown provider

I'm encountering an issue while attempting to implement modals in angular $modalProvider <- $modal <- User.Ctlr Below is my app.js file 'use-strict'; var App = angular.module('App', ['ui.bootstrap']); And here ...