Using Vuex to fetch information from Laravel

As a newcomer to the world of vue/vuex, I find myself immersed in a laravel project that utilizes these technologies for its front end. Needless to say, I am struggling to grasp the intricacies of it all.

My current challenge involves retrieving the folder_path of an episode. The API url in question is structured like this

The alphanumeric string "1602ff28-fd57-473a-9583-1322ff8fd383" represents the episode UID

{"data":{"type":"episodes","id":"1602ff28-fd57-473a-9583-1322ff8fd383",...,"folder_path":"\/home\/xxx\/xxx\/public\/downloads\/episodes\/series\/The Curse of Oak Island\/The Curse of Oak Island - Season 01\/The Curse of Oak Island - S01E01.mp4"},... }

I specifically require the following snippet:

"folder_path":"/home/xxx/xxx/public/downloads/episodes/series/The Curse of Oak Island/The Curse of Oak Island - Season 01/The Curse of Oak Island - S01E01.mp4"

Within my .vue file, the structure is as follows:

<template>
    <div class="hello">

    </div>
</template>

<script>
export default {
  name: 'hello',
    actions: {
      episode_folder(context, payload){
         // GET /api/episodes/{id}
         axios.get(payload.url).then((response) => {
               console.log(response.folder_path);
         });
      }
    }
}
</script>

Despite following this setup, nothing gets printed to the console. Additionally, I am unsure about how to integrate {id} within my payload.url

There seems to be a crucial piece of information that eludes me at the moment, leaving me temporarily stuck.

Answer №1

After attempting to provide an answer in a comment, I realized it wouldn't suffice.

1)

I'm unsure how to properly utilize {id} within my payload.url

If you want to include {id} in your payload.url, you can achieve this through simple string concatenation:

payload.url.concat(`/${id}`)

2) Your Vuex logic is misplaced 🙈

This code belongs in a store.js file (or ideally a Vuex module but let's not complicate things). Here's an example of how your store.js should be structured:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {},
    actions: {
        episode_folder(context, payload){
         // GET /api/episodes/{id}
         axios.get(payload.url).then((response) => {
             // Handle successful response by invoking a mutation
         }).catch(err => console.log(err));
      }
    },
    mutations: {}
});

export default store;

3) You're accessing the wrong object to extract data from the API response When using Axios, the response from an API call is encapsulated within a data object. Therefore, you should access the data like so:

response.data.attributes.folder_path

4) Invoking your action from Vuex

To keep it simple, just call your action in the mounted hook of your component like this:

this.$store.dispatch('episode_folder', {
    url: 'https://example.com',
    id: '1602ff28-fd57-473a-9583-1322ff8fd383'
})

5) For further guidance Vuex is quite extensive and delving deeper into it here would make this answer never-ending 😂. I highly recommend exploring more about Vuex

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

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

Send JSON information to a Spring Boot server application

I am brand new to working with Spring Boot. Currently, I am attempting to send registration form data (in JSON format) from a Vue frontend to a Spring Boot backend. However, the backend always indicates that the received data is null. How can I properly re ...

Exploring the option of integrating Vuetify snackbar as a universal custom component in Vue.js

I recently implemented a Snackbar to display success messages in Vue.js and now I want to create a global custom Snackbar component. <template> <div name="snackbars"> <v-snackbar v-model="snackbar" :colo ...

Using Laravel allows for the implementation of a personalized validation message

I created a custom rule in Laravel 5.5 and configured a custom translation for it in the lang validation file. Here's how I set it up: 'custom' => [ 'validate' => [ 'correct_password' => 'The :a ...

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

How to dynamically order components in Vue?

Any help you can offer in advance will be greatly appreciated. I am currently working on an application that utilizes Vue's dynamic component tag feature. If you'd like to learn more about dynamic components in Vue, please check out this link. ...

Navigating in Vue Router without triggering the next() function

Currently, I am working on a solution to redirect my Single Page Application (SPA) to a different route in case of validation failure. To achieve this, I am utilizing the beforeRouteEnter and beforeRouteUpdate methods to execute a function for this purpose ...

Is the inclusion of @vue/composition-api in devDependencies warranted?

Is it recommended to add @vue/composition-api to the dependencies section of the package.json instead of devDependencies? I noticed that on the npm registry it is listed under dependencies. ...

Tips for establishing a connection between two articulate models

I am handling two Models: Users and Appointments class Appointments extends Model { use HasFactory; protected $fillable = [ 'business_id', 'user_id', 'subject', 'description', ...

What are the reasons for being unable to access the HTML canvas in Vue?

I am currently working on creating a canvas element in Vue, but I seem to be encountering issues with the canvas instance. It appears that I may not be declaring or utilizing it correctly, as I am receiving the following error: TypeError: Cannot set pro ...

The v-autocomplete component's watcher is not functioning as intended

Despite numerous attempts, I have been unable to get my watcher to work properly with the v-autocomplete component. <template> <v-app id="inspire"> <v-content> <v-form ref="form" v-model="valid" :lazy-validation="lazy"> ...

Retrieve the data of the current component from the slot template

This specific vue component showcases a CardGroup template with a headerRight slot. The content of the slot includes a message displaying the total number of items, accessed through the this.total data property. <template> <CardGroup> ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

What is the best way to divide my Vue.js project into separate sections for development and testing purposes?

I am looking to split my vuejs frontend project into two sections: development and testing. For the development section, I want to work locally and make requests to the example:8010 url, while for the testing section, I need to send requests to the example ...

Issue with Nuxt: Module needs to export a function: @turfhelpers [ERROR]

Can someone explain why I am receiving the error message Module should export a function: @turf/helpers after adding @turf/helpers to my buildModules in nuxt.config.js? nuxt.config.js // Plugins to run before rendering page: https://go.nuxtjs.dev/config-p ...

Tips on extracting only abstract JSON data from an API response?

Description I'm attempting to send a request to an API using PHP cURL $access_token = $tokens['access_token']; $headers = array( "Authorization: Bearer " . $access_token ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,env('USE ...

Encountering a Troubleshooting Issue with ArcGIS JS API 4.7 and N

Recently, I have been attempting to set up ArcGIS JS API 4.7 using npm for a Vue.JS project. However, when I execute the command npm install arcgis-js-api I encounter an error with NPM: npm ERR! code E404 npm ERR! 404 Not Found: @dojo/i18n@~0.6.0 Althou ...

Encountering a Laravel error related to "SymfonyComponentHttpKernelExceptionHttpException"

After transferring my Laravel and Vue JS application to our server, I encountered an error that reads: Symfony\Component\HttpKernel\Exception\HttpException A similar issue was reported here, but unfortunately no solution was provid ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

What is the function of the # symbol within a <template> in the context of v-data-table in Vue JS?

I recently started learning Vue.js and was given a project example to review. Can someone please explain what the code <template #['item.amtv_start_sales_date'] = "{item}"> actually does in this context? Any help would be greatly appreciate ...