When attempting to utilize the Vuex store in a child component, it appears to be ineffectual

I'm experiencing an issue with the vuex-Store. There is a state in my store that is not being updated when the Action is called. Can anyone help me out here? The problem lies with the "selectedHive" state. The axios call is functioning properly and getting the correct response. However, the Object is not being updated in the store.

Here are the relevant files:

Store:

import merge from 'vuex'
import axios from 'axios'

export const state = () => ({
  selectedHive: {},
  hivesList: []
})

export const mutations = {
  set(state, hives) {
    state.hivesList = hives
  },
  add(state, value) {
    merge(state.hivesList, value)
  },
  remove(state, { hive }) {
    state.hivesList.splice(state.hivesList.indexOf(hive), 1)
  },
  setHive(state, hive) {
    state.selectedHive = hive
    console.table(state.selectedHive)
  }
}

export const actions = {
  async get({ commit }) {
    await this.$axios.get('http://localhost:8080/api/v1/hives').then((res) => {
      if (res.status === 200) {
        commit('set', res.data)
      }
    })
  },
  async show({ commit }, params) {
    await this.$axios
      .get(`http://localhost:8080/api/v1/hives/${params.id}`)
      .then((res) => {
        if (res.status === 200) {
          console.log('ID: ' + params.id)
          commit('setHive', res.data)
        }
      })
  },
  async set({ commit }, hive) {
    await commit('set', hive)
  },

  async getHive({ commit }, params) {
    console.log('getHive called' + params)
    return await axios
      .get(`http://localhost:8080/api/v1/hives/${params}`)
      .then((res) => {
        console.log(res.data)
        console.log(typeof res.data)
        commit('setHive', res.data)
      })
      .catch((err) => {
        console.log(err)
      })
  }
}

Component:

<template>
  <div class="div-box">H: {{ selectedHive }}</div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  props: {
    hiveid: {
      type: String,
      required: true
    }
  },

  async fetch({ store }) {
    this.getHive(this.hiveid)
    console.log('Passing: ' + this.hiveid)
    await store.dispatch('hives/getHive', this.hiveid)
  },

  computed: {
    ...mapState({
      selectedHive: (state) => state.hive.selectedHive
    })
  },
  created() {
    console.log('id: ' + this.hiveid)
    this.getHive(this.hiveid)
  },

  methods: {
    ...mapActions('hives', ['getHive'])
  }
}
</script>

<style scoped>
.div-box {
  /* width: 49%; */
  border: 1px solid black;
  padding: 10px;
}
</style>

Parent Page:

<template>
  <div>
    <h1>Locations</h1>
    <div v-for="loc in locationList" :key="loc.id">
      <div class="div-box">
        u-Id: {{ loc._id }} <br />Name: {{ loc.name }} <br />
        Adresse: {{ loc.adress }} <br />
        Koordinaten: {{ loc.longitude }} , {{ loc.latitude }} Völker: <br />
        <div v-for="hive in loc.hives" :key="hive._id">
          {{ hive._id }}
          <hiveIcon :hiveid="hive.hiveId" />
        </div>
      </div>
      <br /><br />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import hiveIcon from '@/components/hiveIcon'

export default {
  components: {
    hiveIcon
  },

  computed: {
    ...mapState({
      locationList: (state) => state.locations.locationsList,
      selectedLocation: (state) => state.locations.selectedLocation,
      hivesList: (state) => state.hives.hivesList,
      selectedHive: (state) => state.hives.selectedHive
    })
  }
}
</script>

<style scoped>
.div-box {
  /* width: 49%; */
  border: 1px solid black;
  padding: 10px;
}
</style>

Answer №1

It seems like the issue might be related to how you structure your state and access it.

Currently, your state looks like this:

export const state = () => ({
    selectedHive: {},
    hivesList: []
})

However, when mapping, you are accessing hive before selectedHive:

...mapState({
    selectedHive: (state) => state.hive.selectedHive
})

Consider accessing it directly, like:

selectedHive: (state) => state.selectedHive

UPDATE:

Have you tried setting up a watcher on the selectedHive property?

    watch: {
        selectedHive: {
            deep: true,
            handler() {
                console.log('selectedHive has changed');
            }
         }
   }

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

Prevent Float Filtering in AngularJS

As I work on creating a directive in AngularJs, I am facing an issue. The directive is supposed to receive a JSON object from the app controller and display its content accordingly. To better illustrate my problem, I have created a simple demo which can b ...

Using JSON to interact with Response APIs across various programming languages

I am currently facing an issue while attempting to return a response from my API in the language selected from the header using: Accept-Language: es-MX or Accept-Language: en-US function getLanguage(req, res, next) { let lang = req.acceptsLanguages(&a ...

Connecting two COTURN servers for seamless communication

Currently, I have a total of 5 webRTC peers connected through the COTURN server (turnServer1). These peers are all behind symmetric NAT, requiring the use of the TURN server to establish connections. However, due to the media streams with audio and video b ...

Reasons why the intermediate state may not be visible to the user right after calling setState() in the componentDidMount() lifecycle method

While exploring the React Docs at https://reactjs.org/docs/react-component.html According to the documentation, it is stated that you may call setState() immediately in componentDidMount(). This action will result in an extra rendering, however, it will ...

Is the concept of client fanout truly beneficial?

I'm in the process of constructing a community platform on firebase that features timelines and posts similar to those found on Facebook. When a user creates a post, it should automatically appear on the timelines of their followers. Google proposes ...

Hovering triggers the appearance of Particle JS

I am attempting to add particle js as the background for my website. I have tried implementing this code snippet: https://codepen.io/nikspatel/pen/aJGqpv My CSS includes: position: fixed; z-index: -10; in order to keep the particles fixed on the screen e ...

Can a limit be imposed on the horizontal scrolling distance of a component to automatically wrap text?

I'm looking for a way to enable users to horizontally scroll across text within a React component while still maintaining a set width larger than the component's bounding rectangle. This would allow for regular paragraphs without any line breaks ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

extract information from a document and store it in an array

As I delve into the realm of programming, I find myself grappling with the best approach to extract data from a file and store it in an array. My ultimate aim is to establish a dictionary for a game that can verify words provided by players. Despite my no ...

Deselect the DOM element

Here is a jQuery code snippet: $(document).ready(function () { $(".story-area > h1, .story-area > p, .story-area > div > p").text(function () { return convertString($(this).text()); }); }); Additionally, there is a function de ...

Encounter a scope.router.go error when using Vue.js with System.js

During my testing of a Vue.js-System.js app before transitioning to webpack2, I encountered an issue with the routing pattern. In the OPA Memberships component, when clicking on a link, I aim to request a Registration page from the router. To achieve this ...

What is the best way to display a segment of an SVG on a Canvas element?

Main Issue: The main objective here is to display a specific part of an SVG image on a fixed size Canvas element within a web page. Approach I Tried: After considering various options, such as using CanVG, I thought about utilizing the viewBox attribute ...

Check for the presence of a file in the directory and if it exists, load

Attempting to explain this query may lead to confusion. I have been searching for an answer for approximately three days with no success. It appears that the task at hand is either impossible or so straightforward that no one has encountered the need to in ...

Retrieving the selected value from a dropdown menu without having to click on a

I'm facing an issue with 2 dropdown menus outside of an HTML table that is generated by PHP code. There's a submit button within this table, and here's how it's set up: <!doctype html> Select Year: ...

Tips on capturing JSON data for export and sending it to a specific URL

After implementing the recommended code changes, I still cannot see any updates on the specified WordPress page - . It appears that there may be a login information or other issue preventing me from viewing the changes. Here is the updated code: // New ...

Is there a way to alphabetically and numerically organize a table in vue.js?

Currently, I am implementing sorting functionality for a table using vue.js. While I have successfully achieved ascending sorting for numbers, I am facing challenges with getting the descending and alphabetical sorting to function properly. Below is the H ...

The ambiguity surrounding the timing of decorator invocation in TypeScript

My understanding was that decorators in TypeScript are invoked after the constructor of a class. However, I recently learned otherwise. For example, the primary response on this thread suggests that Decorators are called when the class is declared—not wh ...

Showcasing a dynamically created JSON document on a basic web page

Looking for a solution to display the contents of a result.json file generated by my Java tool on a simple website. I am aware that accessing local files directly with JavaScript is not possible, so seeking alternative methods that do not involve using a w ...

Verify in Mongo if a specific document is already present

Currently in development of my MEAN app, the client-side sends a $http POST request to my API with a JSON array containing soundcloud track data specific to each user. My goal now is to save these tracks to my app database within a 'tracks' table ...

Tips on adding a watermark to multi-page PDFs using an image as the watermark

I am currently working on embedding a watermark onto every page of a PDF file using the image-watermark library. So far, I have successfully added a text watermark to files with only one page but now I am exploring ways to extend this functionality for mul ...