Utilize the fetch function within a Vuex action

After creating a store action to fetch an API, I encountered an error when trying to dispatch it from the component's created lifecycle hook. The error message displayed was 'Cannot read property 'dispatch' of undefined'. Despite researching similar questions, none of the suggested solutions resolved this issue.

I attempted to dispatch the action in a normal method as well, only to encounter the same error.

In the store.js file:

import Vue from "vue";
import Vuex from "Vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    categories: []
  },
  mutations: {
    SET_CATEGORIES(state, categories) {
      state.categories = categories;
    }
  },
  actions: {
    getCategories({ commit }) {
      return fetch("https://api.chucknorris.io/jokes/categories")
        .then(response => {
          return response.json();
        })
        .then(jsonObj => {
          commit("SET_CATEGORIES", jsonObj);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
});

Below is the component where the dispatch is being attempted -

<script>
export default {
  data() {
    return {
      joke: "",
      categories: [],
      selectedCat: ""
    };
  },
  computed: {
    disabled() {
      if (this.joke) {
        return false;
      } else {
        return true;
      }
    }
  },
  methods: {
    addToFavs: function() {
      this.$emit("pushJoke", this.joke);
      this.fetchJoke();
    }

  },

  created() {
    this.$store.dispatch('getCategories');
  }  
};
</script>

Could you please lend your expertise in identifying what might be causing this issue?

Answer №1

To begin, start by including

import { fetchActions } from 'redux'

within the script section of your code.

Next, add to functions

methods: {
  ...fetchActions([
     'retrieveData'
  ])
.
.
}

and update your custom method to

customMethod() {
  this.retrieveData()
}  

Additionally, consider creating a redux action to replace the

this.$emit("pushData", this.data);
line you currently have, and map it in a similar manner as you did with retrieveData

Answer №2

The reason why you're encountering this issue is because you forgot to include your Vuex store option when creating the root Vue instance. To fix this, make sure to import your store and attach it to your Vue instance.

import { store } from '.store'

const app = new Vue({
  store
})

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

Store the input fields of the chosen table row into an array for iterative processing

I need help with extracting input fields from a specific row in a table and adding them to an array. My goal is to loop through this array later. This is how I currently approach it: let selectedTr = []; let arr = []; $('td input:checked').eac ...

Capture the user's input data and use it to populate the value of a select option

I'm facing an issue with a dropdown list that has different values. My goal is to display a hidden div with the id "othertype" whenever I select the "Other" option and then type in an input field to save that data. However, this functionality is not w ...

Leveraging the power of ReactJS for efficiency in executing multiple API calls concurrently

I'm encountering an issue with the following code snippet: let tmpContributors = [...this.state.contributors]; for (let i = 0; i < 10; i++) {//10 most active contributors due to performance and github limits contributorPropertiesPromises.pus ...

Having difficulty creating a snapshot test for a component that utilizes a moment method during the rendering process

I am currently testing a component that involves intricate logic and functionality. Here is the snippet of the code I'm working on: import React, { Component } from 'react'; import { connect } from 'react-redux' import moment from ...

Effortlessly create a seamless transition in background color opacity once the base image has finished

I've set up a div with a sleek black background. Upon page load, I trigger an API request for an image, which is then displayed in a secondary div positioned behind the main one. After this, I aim to smoothly transition the overlaying div's opaci ...

Why isn't nesting directives working in AngularJS?

I am facing an issue with one parent directive and multiple child directives. My requirement is to nest one directive inside another, resulting in the use of multiple directives. Could someone assist me in identifying any errors in this code or provide e ...

Sort with AngularJS: orderBy multiple fields, with just one in reverse

Currently, I am faced with the challenge of filtering data based on two variables: score and name (score first, followed by name). This task involves various games, some of which have scores in reverse order (like golf) while others maintain a normal scor ...

Using additional properties when referencing another Mongoose schema

var UserSchema = new Schema({ job : [{ type : mongoose.Schema.Types.ObjectId, experience : String, grade : String, ref: 'Company'}] }); User's profile can include multiple jobs. The process of adding a job to the user is a ...

Is it feasible to implement automatic window closure on the alternate website?

Imagine I have a website, let's say http://myownsite.com, and my desire is to execute a script that will open a new window on Safari or any other browser for a site which I do not own: http://theothersite.com If I lack control over that specific site ...

Sending a delete request mutation using local storage: a step-by-step guide

I'm currently developing a recipe application and facing an issue with the delete button functionality. Instead of deleting the selected recipe from Vuex with local storage, it deletes the most recent one added to the Vuex array. Below is the code sn ...

Ajax experiences trouble with a intricate sequence of characters

How can I successfully send the following string to a spring MVC controller using ajax: (?=^.{8,}$)(?=.+\d)(?=.+[!@#$%^&]+)(?!.*[\n])(?=.+[A-Z])(?=.+[a-z])$ I am encountering a 400 bad request error and it is not leaving the client side. An ...

Transferring scope between pages without the need for an angular service definition

Looking to open a new JSP page while passing the $scope in order to utilize an array response generated in the initial page. Example from test.js file: (function() { 'use strict'; angular .module('test', []) .control ...

Dealing with errors in Mongoose within a Node.js application: A guide

I'm currently working on a node.js application using express, mongoDb, and mongoose. While the app is able to save users without any issues, I am facing an error in the code snippet below. The console always displays an error message even when the use ...

Tips for utilizing an IF statement in a Protractorjs Spec.js document?

I am attempting to execute the spec.js file across multiple browsers using Multicapabilities in conf.js. However, I specifically want a certain line of code to only run for Internet Explorer. I have tried putting this code snippet inside an IF statement w ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

"Enhancing User Experience with Dynamic Text Replacement through CSS and JavaScript

I'm currently working on implementing some unique features with JavaScript and CSS that I'm having trouble figuring out. Here's the progress I've made so far: http://codepen.io/melissall/pen/PPWPQE One of my goals is to center the h ...

What is the most efficient way to organize JSON data in a tree structure using JavaScript?

I have a JSON data structure that I need to transform into a different format. The original JSON format: values = an array containing objects that need to be filtered by action === 'commented' comment = an object with the comment, n Tasks, and ...

Change to the camera view after the three js has finished loading

Is there a way to switch to a camera once an object with a perspective camera is loaded? I have an avatar object that contains a perspective camera and I want to use it either directly upon loading or switch to it afterwards. I've tried using orbit co ...

Issue encountered while implementing search functionality with pagination in Laravel using Vue.js and Inertia

Recently, I have embarked on my journey to learn Laravel 8 along with vuejs and inertiajs. My current challenge involves creating a pagination search table. Despite diligently following tutorials, I keep encountering errors. Below is the code snippet for ...