Retrieving data objects from axios call in Vue and passing them to the controller

Currently, I am using Vue within Laravel and facing an issue with retrieving data from a controller function that I am accessing. My goal is to use this data in the data() section of my Vue template.

Though I am aware that the controller function returns the necessary data, I am unsure about how to handle the return/response in the axios call in order to effectively populate the data() function in Vue.

Below is the code snippet from the Blade/Vue template:

import moment from 'moment'
export default {
    name: 'calendar',
    data () {
        return {
            events: [
                {
                    title: 'test',
                    allDay: true,
                    start: '2019-08-17',
                },
            ],
            config: {
                defaultView: 'month',
                eventRender: function(event, element) {
                    console.log(event)
                }
            },
        }
    },
    created() {
        this.fetchTasks();
    },
    methods: {
      fetchTasks() {
        axios.get('/landing/tasks' )
            .then((response) => {
                // handle success
                this.assetOptions = response.data;
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .finally(function () {

        });
    }
}

Regarding the Route:

Route::get('/landing/tasks', 'landingController@getTasks')
    ->name('landing/tasks');

And here is the Controller:

public function getTasks()
{
    $getTask = Task::getTaskForLanding();

    $result = array();
    foreach($getTask as $id => $task){
        $result[$task->task_id][] = $task;
    }
}

Answer №1

If you are confident that the Controller is providing the necessary information, the only missing piece is declaring assetOptions. In order to later assign response.data to assetOptions, you must first declare it within the data function.

data() {
    return {
    ...
    assetOptions = []; // assuming you are anticipating an array
    ...
    };
}

Once you have completed this step, everything will be good to go.

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 in installing opensea-js using NPM

While working on my project, I encountered an issue when trying to install opensea-js as a dependency. My Node version is v14.16.0 and NPM version is v7.7.5. Every time I run the command npm install --save opensea-js, it results in an error. I attempted c ...

The uploaded file in Laravel does not seem to be visible in the designated "public/storage" directory

After executing the command: php artisan storage:link, a new folder is created at /public/storage. Next, I have a piece of code that handles uploaded files: // Here we extract the original name and extension of the file // We then generate a new filename ...

How can I put a row at full-width in a Material-UI table in React

I need assistance with displaying data in a table using JSX code: const StudentsTable = (props) => { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple ...

Avoiding the storage of POST data in JSON format

Here is some code I am working with: var jsonString = "some string of json"; $.post('proxy.php', { data : jsonString }, function(response) { var print = response; alert(print); }); And this P ...

Guide on implementing dynamic rowspan in tables using vue.js

I am trying to create a table similar to the one in the example photo. https://i.sstatic.net/fkXDx.png I attempted to connect rows using rowspan and wrote some code for it, but unfortunately, I encountered an error in the browser. To start with, here is ...

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

Serve as a proxy for several hosts with identical URL structures

I've been utilizing the http-proxy-middleware to handle my API calls. Is there a way to proxy multiple target hosts? I've searched for solutions in the issues but still haven't found a clear answer. https://github.com/chimurai/http-proxy-m ...

When implementing useFetch with onMounted in Nuxt3, data is not being fetched upon directly opening the link

In my project, I have implemented the useFetch function in the composition api to fetch data. The function is then called within the onMounted hook of components. Here is how it's done: Custom Composable: useShows.ts export function useShows(){ ...

several parameters for the `ts-node -r` options

Can I include multiple require statements in the package.json script before running with ts-node -r? "scripts": { "start": "ts-node -r dotenv/config newrelic src/index.ts", } I'm having trouble adding both "dotenv/config" and "newrelic" si ...

Tips for updating the firebase access_token with the help of the next-auth credentials provider

Can anyone help me with refreshing the Firebase access token when it expires? I need the token for API authentication, but I can't find any information online regarding next-auth and Firebase. Currently, I am able to retrieve the access token but str ...

Debugging the Force-Directed D3 Graph

I stumbled upon a fantastic article that provided a detailed guide on creating a beautiful D3 force layout graph. However, I'm facing some difficulties with the JSON source: The "links" attribute in the author's JSON doesn't seem clear to m ...

Tips on allowing a rectangle to be draggable using HTML5

I have been experimenting with resizable and draggable rectangles in HTML5. I've managed to create resizable rectangles, but I am having trouble getting them to drag using mouse events. You can view my JSFiddle code at the following link: here. / ...

What is the best way to embed two controllers within an AngularJS webpage?

Currently, I have a Web Forms ASP.NET website that I am trying to enhance by adding an AngularJS page. This page is meant to interact with my RESTful Web API to display quotes for selected securities upon button click. While the Web API calls work when dir ...

What is the best way to implement ajax loading on scroll?

I need to implement lazy loading for multiple ajax pages on my website. I want the ajax content to load dynamically as the user scrolls down the page, similar to infinite scroll or lazy image loading. $('.lazy_content').on('load', fu ...

Updating the filter predicate of the MatTableDataSource should allow for refreshing the table content without needing to modify the filter

Currently, I am working on dynamically altering the filterPredicate within MatTableDataSource to enhance basic filtering functionalities. I want to include a fixed condition for text filtering (based on user input in a search field) for two string columns ...

Validating Forms using Javascript

I'm struggling to understand why I'm not getting any error or success messages when I click the submit button. My goal is to validate strings in an HTML form to ensure they are not null or too long. Both the developer's tools and the Online ...

Retrieve data from a Rails controller using Ajax

Seeking assistance and insight for a coding dilemma I'm facing. In my Rails application, I have a controller named get_songs that retrieves a hash of songs belonging to the currently logged-in user. What I'm trying to achieve is to fetch this dat ...

Obtain the session value in React

Currently, I am working on a React app along with a server-side application. I have successfully created a user session on the server side and now I want to retrieve its value in my React app. Can someone guide me on how to achieve this? const [user,setUse ...

Advanced Layout: Angular Event window:scroll not Triggering

One issue I am facing is that the event gets triggered on some components but not others. For example, it fires as soon as I route to all other components except for the Landing component. Below are my code snippets: <-- Main Component --> <div c ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...