Printing 'undefined' to the console after making an API call with Vue

After authenticating and fetching data from a 3rd party API in my Laravel Controller, I'm encountering an issue where 'undefined' is being logged in the console instead of the actual data that I want to store in a Vue component.

I've tried various approaches, such as using a get method instead of fetch, but unfortunately, I still end up with undefined being logged. I also did some research on arrow functions, although I am not currently implementing them in this code.

data() {
    return {
        tickets: [],
    };
},

created() {
    this.fetchTickets();
},

methods: {
    fetchTickets() {
        fetch('/api')
        .then(res => {
            this.tickets = res.json;
        })
        .then(res => {
            console.log(res.json);
        }) 
    }
}

Essentially, I am looking to successfully retrieve a collection of data from a PHP backend request that interacts with a 3rd party API. This data should then be stored within my Vue component, rather than just logging undefined as it currently does.

EDIT Backend request in PHP

 $response = $client->get('v1/tickets/search.json', [
        'query' => ['statuses[]' => 'active', 'assignedTo[]' => 314955, 
        'sortDir' => 'desc', 'sortBy' => 'updatedAt']
    ]);

    $json = (string)$response->getBody()->getContents();
    $decoded = json_decode($json, true);
    return collect($decoded);

Route: Route::get('/api', 'ApiController@getTickets',);

Answer №1

fetch function returns a promise that contains the response res. (This response is just the HTTP data, not the actual JSON content.)

To extract the JSON body from the response, we utilize the json() method.

If you're interested in learning more, check out this resource on using fetch.

fetchItems() {
    fetch('/api')
    .then(res => res.json()) //returns a promise to extract JSON body data
    .then(resJson => {
        this.items = resJson
        console.log(resJson);
    }) 
}

Answer №2

Prioritize returning data before proceeding to the second promise.

retrieveTickets() {
    fetch('/api')
    .then(res => {
        this.tickets = res.json;
        return res;
    })
    .then(res => {
        console.log(res.json);
    }); 

Answer №3

Make sure to include the return statement in the initial promise

fetch('/api')
  .then(res => {
      return res.json();
   })
   .then(data => {
     // data is only accessible within this scope
     console.log(data);
   }) 

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

Is there a way to incorporate HTML code into a fullCalendar 4 event title?

Is it possible to add HTML content to an event title using eventRender in FullCalendar version 4? document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

Create a router link in Vue using the command "Vue

I have a Vue application that displays videos. I am looking to automatically generate a random router link every time I click on: <router-link to="/video/this_value_to_be_random">Random video</router-link> Within the component: <vue-vide ...

What is the best approach to gather both the intersection and the complements of two arrays in a single operation?

Comparing Arrays - const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; Initializing Arrays - const matches1 = []; const matches2 = []; const unmatches1 = []; Array Matching Process - for (const line of source) { const line2Match = target.fi ...

Determine the name of the time zone using JavaScript

Currently, I am developing a React application and facing an issue where the timezone is detected as 'Etc/GMT-1' instead of the desired format 'Africa/Bangui'. This problem seems to be specific to my machine as it persists even when usi ...

What is the method for obtaining a unique id that changes dynamically?

Having trouble accessing the dynamically generated ID in jQuery? It seems to work fine in JavaScript but not in jQuery. Here's an example of the issue: My jQuery code: var img = $("#MAP"+current_img_height); $("#map").css({'height': img.h ...

The tension settings in Chart.JS appear unusual

I recently updated to ChartJS v4.0.1 and noticed a new option called tension for curving the line chart. However, I'm not satisfied with how it looks. The tension option ranges from 0 to 1, and I've experimented with different values to enhance ...

Press the button to automatically scroll to a designated div section

One of the challenges I'm facing involves a fixed menu and content box (div) on a webpage. Whenever I click on the menu, the content box should scroll to a specific div. Initially, everything was working fine. Here is a sample of it in action: http ...

Is there a way to incorporate unique shapes into mxGraph?

What is the process for including custom shapes in mxgraph? Image Representation of Shapes Check out these BPM shapes ...

What is the best method for uploading images and form content simultaneously in a Vue application?

How can I simultaneously upload images and form content? Is it possible to upload both to the client first and then to the server together with the form content? I'm looking to submit the form content along with the image to the server in one go when ...

Tips for eliminating the default arrow on the HTML select tag?

I am currently utilizing vuejs along with tailwindcss and I am trying to figure out how to get rid of the default arrow from an HTML select element. Despite my attempts to remove it by using CSS properties like -moz-appearance, -webkit-appearance, -ms-appe ...

Implementing Dynamic CSS Styles in AngularJS

Essentially, I am facing a challenge on my page where a control needs to toggle two different elements with two distinct CSS classes upon being clicked. While I have successfully managed to toggle one of the controls, the other remains unchanged. Here is ...

Automatically, the "ng-hide" class gets added despite using the correct syntax for ng-show

I am trying to dynamically show/hide a tr tag within a table based on the value of a scope variable in the controller. Despite writing the code correctly, I am facing an issue where the "ng-hide" class is automatically added to the tr tag every time it is ...

Direct attention to the modal display

I'm having trouble auto-focusing an input field when a modal is displayed. Here's what I've tried, but it doesn't seem to be working: jQuery(document).ready(function($) { $('#myModal').on('show.bs.modal', functi ...

Developing a personalized language setting in Nuxt.js for internationalization

I'm facing an issue with my application where I am struggling to figure out how to create a custom locale. For example, I have routes like /hello and /ja/hello, where the first route is for the default English language and the second one is for Japane ...

Converting October website pages' formatting into JSON for a Vue.js application

In order to create a Vue menu in OctoberCMS, I have developed a plugin that extracts the page structure from October pages into JSON data while maintaining the indentation of pages and subpages. Referring to this post: How to get static page dropdown in O ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

Problem with exporting data from the API to a JavaScript file in Excel format

Instead of receiving actual data in the response, I am getting a set of characters. However, everything works fine when I click on Download file in swagger. Can someone help me diagnose the issue? function downloadDocFile(data: Blob, ext = 'xlsx' ...

What steps should I take to enable Google Maps style on mobile devices?

Hi there! I'm having some trouble styling my Google map. Sometimes the style loads correctly in browsers, and sometimes it doesn't. Another issue I've noticed is that when I view the page on mobile platforms like Android Chrome, iOS Safari, ...

A role requiring coordinates x, y, and z with significant values

http://jsfiddle.net/eho5g2go/ var offset=10000000; ... camera.position.set(offset,offset,400); mesh.position.set(offset-300,offset,0); camera.lookAt(mesh.position); ... animate(); The "offset" variable is crucial for determining the camera and mesh p ...