Failed to retrieve UI data from localstorage while performing an asynchronous action

Whenever I click on a specific "task," it loads correctly and the correct UI with data is displayed. The issue arises when clicking on the link through the browser input window - localhost:port/task/edit/id, or when manually refreshing the page for each "task". How can this problem be resolved?

router.js:

{
            path: '/task/edit/:id',
            name: 'edit-task',
            component: EditView,
},

Snippet of code featuring EditView:

<template>
  <div>
    <task-edit :task="task" v-if="task" :key="taskId"/>
    <p v-else>Loading task...</p>
  </div>
</template>

<script>

export default {
  name: 'EditView',
  components: {
    TaskEdit,
  },
  computed: {
    ...mapState(['tasks']),
    taskId() {
      return this.$route.params.id;
    },
    task() {
      return this.tasks.find((task) => task.id === this.taskId);
    },
  },
  async created() {
    await this.$store.dispatch('retrieveTaskById');
  },
};
</script>

store.js with actions for loading tasks:

...
  retrieveTaskById({ state }, taskId) {
        console.log('Loading task from localStorage...');
        state.tasks.find(task => {
            console.log(task.id, 'Task loaded')
            return task.id === taskId
        });
    },
...

Below are the console.log outputs when manually navigating to the "edit" page:

Loading tasks from localStorage...

Here are the outputs when navigating from the "home" page:

Loading task from localStorage... 1 'Task loaded'

Answer №1

One issue I found in your code snippet was that you forgot to pass the taskId to the action 'retrieveTaskById'. I have resolved this problem and implemented some enhancements.

// State
retrievedTaskById: {}

// Mutation
setRetrievedTaskById({ state }, payload) {
    state.retrievedTaskById = payload
}

// Action
retrieveTaskById({ commit }, taskId) {
    const task = state.tasks.find(task => task.id === taskId);
    commit('setRetrievedTaskById', task)
}

// Getter
retrievedTaskById({ state }) {
    return state.retrievedTaskById
}

<template>
  <div>
    <task-edit :task="task" v-if="task" :key="taskId"/>
    <p v-else>Loading task...</p>
  </div>
</template>

<script>
export default {
  name: 'EditView',
  components: {
    TaskEdit,
  },
  computed: {
    taskId() {
      return this.$route.params.id
    },
    task() {
      return this.$store.getters.retrievedTaskById
    }
    // Same: ...mapGetters(['retrievedTaskById']),
  },
  created() {
    this.$store.dispatch('retrieveTaskById', this.taskId)
  }
};
</script>

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

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Discovering the process to create an onclick function with node.js code

index.html: <html> <h2>Welcome To User Profile Page !!!</h2> <button type="button">Edit Profile</button> <button type="button">Logout</button> </html> On my webpage, I have two buttons - Edit Profile and Lo ...

The jQuery newsfeed is powered by the $.each() method

I'm having trouble setting up a newsfeed on my website. It's supposed to display all the current news and exclude any expired ones. I have a webpage where I can add news, so the JSON data is constantly changing. Here's an example of the PHP ...

Caution: Using Blade template data with Vue may trigger a warning

I encountered an error related to Vue [Vue warn]: Property or method "product" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializi ...

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click. pauseTask: function() { this.isOpen = !this.isOpen; this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume'; }, While it works flawle ...

Exploring the intricacies of Implementing Chromecast Networks, with a curious nod towards potentially mirroring it with

In my current project, I am aiming to replicate the functionality of a Chromecast on a Roku device. To achieve this, I need to first discover the Roku using UDP and then send an HTTP POST request to control it. During a recent developer fest where I learn ...

JavaScript code: "Retrieve the div element and append metadata to the HTML file

Currently, I am utilizing the subsequent technique to save a target tag on my webpage as an HTML file. function retrieveHtml(filename, elId, format) { var htmlEl = document.getElementById(elId).innerHTML; if (navigator.msSaveBlob) { // IE 10+ ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Bidirectional Data Binding with Computed Setter in Vue.js

Exploring the concept of two-way data binding with a basic example: <template> <input v-model="fullname"/> <input v-model="first"/> <input v-model="last"/> </template> <script> var app = new Vue({ el: '#a ...

Differences between Angular's $injector and Angular's dependency injectionAngular

As a newcomer to Angular, I am exploring the use of $injector and its get function to retrieve specific services. For instance: app.factory('$myService', function($injector) { return { ... var http = $injector.get('$http&apos ...

Determining the value of an element by examining the clicked element

My goal is to determine the remaining balance in my cart based on the selected item. Let's say I have 3 items in my cart, and I choose one that costs $100. Previously, I stated that I had a total of $300. In my HTML code, there are elements with IDs ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

Is it possible for a local variable in Vuex to update with a mapState value, so that changing the local variable will also update

Why is my Vuex object being modified when I assign its value to a local variable and make changes to the local copy? Should I provide my store.js for reference? My code looks like this: data() { return { localObject: [], }; }, computed: ...

How can I retrieve input value using v-on:change and click events in Vue.js?

Currently, I am working on a project within vuejs: template : <b-form-input placeholder="name" type="text" class="d-inline-block" v-model="name" v-on:change="changeInput" /> <b-butt ...

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

I am looking to adjust the width of an element within an Iframe

In my single post, I have a social sidebar on the left side. Currently, the buttons in the sidebar are appearing in different sizes, but I want them all to be the same size as the "Twitter" button. To see the issue, please visit this link. I've tried ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

NodeJS: Extract images based on specified coordinates

Dealing with images that contain text can be a challenge, but by using tesseract and the imagemagick node module, I was able to extract the text successfully. The only issue I encountered was related to the image size. https://i.sstatic.net/XldZC.png For ...