Unable to reach axios within the vuex Store

Below is the code snippet from my store.js file:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios/dist/axios';
import VueAxios from 'vue-axios'

const api = axios.create({
  baseURL: 'mybase.com',
  timeout: 2000,
});

Vue.use(VueAxios, api)
Vue.use(Vuex);
export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  state: {
    name: null,
    YOB: null,
    gender: null,
    city: null,
    daily_goal: null,
    balance: null,
    today_video_count: 17,
    video_credit: 5,
  },
  mutations: {
    updateDailyGoal(state, value) {
      state.daily_goal = value;
    },
    addVideoCredit(state) {
      state.balance += state.video_credit;
    },
    reduceDonation(state, amount) {
      state.balance -= amount;
    },
    setVideoCount(state, count) {
      state.today_video_count = count;
    },
    initialize(state, profile) {
      state.name = profile.name;
      state.YOB = profile.YOB;
      state.gender = profile.gender;
      state.city = profile.city;
      state.daily_goal = profile.daily_goal;
      state.balance = profile.balance;
    },
  },
  actions: {
    submitVideoView({commit}, payload) {
      // this.$http.post('/vid');
      commit('addVideoCredit');
    },
    setDailyGoal({commit}, value) {
      // this.$http.post('/account/daily-goal', {daily_goal: value});
      commit('updateDailyGoal', value);
    },
    init({commit}) {
      // this.$http.get('/account/profile').then(response => {
      //   commit('initialize', response);
      // });
      // this.$http.get('/account/vid-view').then(response => {
      //   commit('setVideoCount', response);
      // });
    },
  },
  created() {
    dispatch('init');
  },
});

I encountered an error stating that undefined doesn't have a post property, indicating that this.$http is not defined. How can I address this issue? Additionally, here is the relevant portion of my main.js file:

import Vue from "nativescript-vue";
import App from "./components/App";
import store from "./store";

new Vue({
  store,
  render: (h) => h("frame", [h(App)]),
}).$start();

I would greatly appreciate any feedback or suggestions on how to enhance this code. I have searched extensively for documentation on setting this up correctly but haven't found anything useful. Please note that I only want the init action to be dispatched once at the start of each user session or app launch.

Answer №1

Using an Axios wrapper for simple HTTP requests may not be necessary. Instead, you can directly import the Axios module into a file and make the requests through it. If desired, you can wrap it as a data adapter.

import axios from 'axios';
const baseUrl = process.env.BASE_URL || '/';
export default {

 get(url, options) {
    return axios.get(`${baseUrl}${url}`, options)
      .then(response => response.data);
  },
  post(url, body, options) {
    return axios.post(`${baseUrl}${url}`, body, options)
      .then(response => response.data);
  },
  update(url, body, options) {
    return axios.put(`${baseUrl}${url}`, body, options)
      .then(response => response.data);
  },
  delete(url, options) {
    return axios.delete(`${baseUrl}${url}`, options);
  },
}

Name the file as EP/index.js, for example. Then in your vuex, you can import that file and use these functions as needed.

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

Enhance your website with a dynamic div zoom feature using the Jquery Zoom

I've been scouring the internet for a jQuery plugin that allows me to zoom in on an image. There are many options out there, but I prefer ones that display the zoomed-in image in a separate area rather than directly on the original image. For example ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Could you explain the distinction among req.path, req.params, and req.query?

I'm curious about the distinctions among req.path, req.params, req.query, and req.body in node.js. Can someone provide an explanation? ...

Design a webpage using material-ui components

I'm struggling to create a layout using material-ui for a child page. Can someone guide me on how to achieve this design? https://i.sstatic.net/TwYR5.png ...

What is the process for updating the Vue template during runtime?

Currently, I am working on a CMS-based Vue page. Within this page, there is a root container that contains two child containers structured as follows: <div id="app"> <div class="above-the-fold">...</div> <di ...

What is the best way to pass a mask without using a plug-in when dealing with an input value in Vue.js?

As someone who has previously implemented the function using pure JavaScript, I am now faced with the challenge of incorporating it into vue.js and determining which lifecycle hooks are best suited for this task. This issue arises as I am a beginner prepar ...

Evolution of Vue lifecycle in Vue2

I am currently in the process of migrating from Vue2 to Vue3. To ensure a smooth transition, I want to make changes that Vue2 can handle before moving on to Vue3. Here are the updates in Vue3 lifecycle: https://i.sstatic.net/x1C76.png My plan is to imple ...

Configuring Vue.js watchers inside a for loop

Exploring the dynamic addition of watchers in Vue.js. The discrepancy between what is desired and what actually happens is demonstrated below in the commented section. As a casual coder, I believe my issue lies more in grasping JavaScript basics rather t ...

Using factories in controllers does not function properly in Angular 1.6

My head is spinning with this one. There are 3 files in play: app.js, app.services.provider.js, admin.js In app.js, I set up my module: (function() { angular.module('myApp', ['ngRoute']).config(function ($routeProvider) { ...

Utilize Vue.js key events for navigating selection with Up, Down, and Enter commands

After performing a search in an array, a list of products is displayed. The user can select a product by clicking on it, which then adds the item to another array for further processing. Everything works perfectly! However, I now need to implement the ab ...

Vue 3 Components Failing to Render

After spending the past 5 hours troubleshooting, I am still unable to pinpoint the issue with my current setup. Essentially, what I am trying to achieve is to have a central "wrapper" application that loads my common codebase, which happens to be a Vue co ...

After reducing the document.domain, the contentWindow of the iframe is met with an Access Denied error

Today, I decided to create an IFRAME dynamically using the following code snippet: var newIframe = document.createElement("iframe"); newIframe.id = 'NewFrame'; newIframe.src = 'NewFrame.html'; document.body.appendChild(newIframe); ...

Click the link to copy it and then paste the hyperlink

I am facing an issue with copying and pasting file names as hyperlinks. I have checkboxes next to multiple files and a share button. When I check the boxes and click on the share button, I want to copy the download URLs for those files. Although I can succ ...

Combining React state value with an HTML tag would be a great way

I am facing an issue while trying to concatenate the previous value with new data fetched from an API using a loop. Instead of getting the desired output, I see something like this: [object Object][object Object],[object Object][object Object] Here is ...

Learn how to utilize DataTable in R Shiny to connect rowCallback and formatStyle functions for customizing the appearance and presentation of your data

Is it possible to utilize both rowCallback and stypeEqual formatting features in one tab when using two tabs to display a data frame in R Shiny? datatable(DF, options = list(rowCallback=JS("function(row,data) { data[0] = data[0] .replace(/NxG/g,&apo ...

Using Javascript to link various arrays filled with file paths and transforming them into an object in a distinctive manner

I've tried countless times to make it work, but it just doesn't seem to work... I have an array that contains multiple other arrays: let arr = [ ["Users"], ["Users", "john"], ["Users", "john", "Desktop"], ["Users", "john", "Docum ...

This asynchronous function will provide a response of "undefined"

Having a challenge with an async function that should return a geocode value: async function getLocationCoordinates(place){ //var str; return googleMapsClient.geocode({ address: place }).asPromise() .then((response) => { response.json.results[0].ge ...

After removing the comment from a single line of code, an error is raised: _http_outgoing.js:359 throw new Error('Cannot update headers once they have been sent.');

Upon removing the comment from this line: return done(null, false, { message: 'Incorrect username' }); in the code snippet below, Node.js runs smoothly without any errors. However, if the line remains commented out, Node.js throws an error as men ...

Ajax, silently transmitting data without refreshing the page

In one of my files, A.php, there is basic information that includes a form with an input field for email and a button. When the user clicks on the button, it triggers a function in JavaScript. <div class="col-md-8"> <input type="email" class="f ...

Transforming a collection of State objects into a series of <li> elements in ReactJS

Just starting out with ReactJS and working on a simple To-Do app where I've added Add,Delete,Edit features. Currently delving into Pagination but struggling with the Display aspect. state = { inputValue: '', todos: [], ...