Issues with Vuex store causing incorrect value retrieval

In troubleshooting this issue, I am encountering a problem. My request to the back end is to retrieve data for display on the front end. The data fetched from the backend consists of recipes stored in an array. Utilizing v-for, I iterate through the array and create router-link elements to navigate to each individual recipe. Upon clicking a recipe link, I aim to display its details on the right side of the screen. However, when retrieving the recipe object from the database upon link click, I notice that the ID retrieved is incorrect.

VUEX MODULE

const state = {
 recipes: [],
 singleRecipe: {}
};

const mutations = {
 'RECIPES_LIST'(state, recipes) {
 state.recipes = recipes;
},
'GET_RECIPE'(state, response) {
 const recipe = response; // THIS IS THE RIGHT RESPONSE 
 state.singleRecipe =  recipe;
 }
}

const actions = {
  initRecipes: ({commit}) => {
  axios.get('http://localhost:3000/recipes')
  .then((response) => {
    commit('RECIPES_LIST', response)
  })
  .catch(err => {
    console.log(err);
  });
  },
  getRecipe: ({commit}, id) => {
   axios.get('http://localhost:3000/recipes/' + id)
  .then(response => {
    const recipe = JSON.stringify(response);
    commit('GET_RECIPE', recipe); // RIGHT RECIPE
  })
  .catch(err => console.log(err));
  },

 const getters = {
 recipes: state => {
 return state.recipes;
 },
  singleRecipe: state => {
   return state.singleRecipe;
  }
};

RECIPE LIST COMPONENT

   <template>
  <div>
    <div class="col-md-6">
      <router-link :to="'/recipes/' + recipe.id"  v-for="recipe in 
 recipes.data">
        <div id="list"  class="panel">
          <div class="panel-body">
            <div class="pull-left">
              <h4>{{recipe.title}}</h4>
            </div>
            <div class="pull-right">
              <img class="img-responsive" :src="recipe.picture" style="width: 80px; height: 80px;">
             </div>
          </div>
        </div>
      </router-link>
    </div>
    <div class="col-md-6">
      <router-view></router-view>
    </div>
  </div>
</template>
<script>
  export default {
    computed: {
      recipes() {
        return this.$store.getters.recipes;
      }
    }
  }
</script>

RECIPE DETAILS COMPONENT

<template>
  <div class="panel" @click="getSingleRecipe">
    <div class="panel-heading">
      <!--<h1>{{recipe.data.title}}</h1>-->
    </div>
    <div class="panel-body">
      <!--<p>{{recipe.data.description}}</p>-->
      <p>Ingredients: </p>
      <ul>
        <li v-for="i in recipe.ingredients">{{i.ingredient}}</li>
      </ul>
      <router-link :to="{name: 'Update', params: {id: id}}"><button class="btn btn-primary">Update Recipe</button></router-link>
      <button class="btn btn-danger" @click="deleteRecipe">Delete Recipe</button>
    </div>
  </div>
</template>
<script>
  import { mapActions } from 'vuex';
  export default {
   data() {
     return {
    id: this.$route.params.id,
    recipe: {}
      }
    },
    watch: {
  '$route' (to, from) {
    this.id = to.params.id;
    this.getSingleRecipe();
        console.log('CHANGEEEEEE' + this.recipe); // GETS RECIPE WITH ID (example 4)
        console.log("ACTIVEEEEEEE ID" + this.id); // GETS RIGHT ID (example id: 2)
      }
    },
   ...mapActions({
      deleteTheRecipe: 'deleteRecipe',
      initRecipes: 'initRecipes',
      getRecipe: 'getRecipe'
      }),
      deleteRecipe() {
    this.deleteTheRecipe(this.id);
    this.initRecipes();
    this.$router.push('/recipes');
  },
      getSingleRecipe() {
         this.getRecipe(this.id);
         this.recipe = this.$store.getters.singleRecipe;
      }
    },
    created() {
      this.getSingleRecipe();
      console.log("CREATED ID" + this.id);
      console.log('CREATEDDDDD ' + JSON.stringify(this.recipe));
    }
  }
</script>

Answer №1

Consider relocating your id property from data to a computed property. It appears that the data.id property may not be reacting to changes in route.params after the component has been rendered.

Another approach to loading a recipe when the route changes is by utilizing the beforeEnter function on your router.

import store from '../store'

beforeEnter: (to, from, next) => {
    store.dispatch(getRecipe, to.params.id)
      .then(() => {
        next()
      })
  }

This method eliminates the need to monitor the router in your component. Utilize mapGetters to access the recipe from the store.

computed: {
  ...mapGetters({
    recipe: 'singleRecipe'
  })
}

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

Experiencing difficulties with parsing JSON data and storing values in a database

I received a JSON response from the server and need help saving the values in a MySQL database using PHP. Can someone please assist me with this? {"fields":[{"label":"Do you have a website?","field_type":"website","required":false,"field_options":{}," ...

Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console: Uncaught Type ...

Sequential execution not functioning properly in NodeJS Async series

Here is the code snippet I am working with: var async = require('async'); var rest = require('restler'); async.series([ function(callback){ rest.get('https://api.twitter.com/1.1/statuses/mentions_timeli ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. My goal is t ...

Can anyone tell me the method to retrieve the id of the current element that initiated the horizonSwiper event in JavaScript?

I successfully integrated horizonSwiper into my php(Yii2) website to display images from different albums in a horizontal row with the ability to scroll left and right. Now, I am looking to implement lazy loading when scrolling or swiping left/right. Howev ...

Begin your meteor project with a remote MongoDB server on a Windows operating system

Currently tackling a project that requires me to integrate my meteor project with a remote MongoDB server on Windows. I successfully set the environment variable (MONGO_URL="DB LINK") from OSX using terminal commands, but I'm encountering difficulties ...

Is it possible to change the style of an element when I hover over one of its children?

Encountered an issue while working with HTML and CSS: //HTML <div> <div class="sibling-hover">hover over me</div> </div> <div class="parent"> <div>should disappear</div> </div> ...

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

Efficient Error Handling in Next.JS with Apollo GraphQL Client

Although the component successfully renders the error state, an uncaught exception is displayed in the console and a dialogue box appears in the browser. How can expected errors be handled to prevent this behavior? import { useMutation, gql } from "@a ...

Display the bash script results on an HTML webpage

My bash script fetches device status and packet loss information, slightly adjusted for privacy: #!/bin/bash TSTAMP=$(date +'%Y-%m-%d %H:%M') device1=`ping -c 1 100.1.0.2 | grep packet | awk '{ print $6 " " $7 " " $8 }'` device2=`pin ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

Attempting to retrieve currentScript is causing a typeError to be thrown

I'm attempting to access a custom attribute that I added to my script tag: <script type="text/javascript" src="https://.../mysource.js" customdata="some_value"></script> To make this work on Internet Explorer ...

Utilize the function specified in an external file

In my project, I have a typescript file named "menuTree.ts" which compiles to the following JavaScript code: define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Menu ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Is it feasible to retrieve information within a behavior in Drupal?

I recently installed the "Autologout" Drupal module, which can be found at . This module includes a timer that ends your session if there is no activity on the page for a set period of time. However, I am interested in adjusting the timer value to better ...

PL/SQL Process in Oracle APEX fails to respond when triggered via AJAX before the page unloads

In my Oracle APEX 4.2 environment, I created a PLSQL process set to execute "On Demand - When this process is called by AJAX." The purpose of this process is to update two member attributes in a collection that I established when the page loaded. Here is t ...

Ways to implement a setTimeout function to return to the initial div element?

I have a unique setup on my webpage with three divs. The first div features an html5 video, the second div contains buttons for interaction, and the third div acts as a thank you page that loops back to the beginning like a photo slide. I have shared my co ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Error: An attempt was made to wrap a property called "find" as a function, but it is

I am currently implementing a test-driven development approach to run my tests. I have successfully run the same test on another application by copying and pasting it, but I encountered an error in this particular test: TypeError: Attempted to wrap unde ...