When fetching from an API (3rd party, I authenticate and get the data in my Laravel Controller) I get ‘undefined’ in the console. to store the data in a vue.js component.
I tried a bunch of different things, including a get instead of fetch, but this also logged undefined. I did some research and read about arrow functions but when not using an arrow function.
data() {
return {
tickets: [],
};
},
created() {
this.fetchTickets();
},
methods: {
fetchTickets() {
fetch(‘/api’)
.then(res => {
this.tickets = res.json;
})
.then(res => {
console.log(res.json);
})
}
}
So, what is the collection made out of the get request I send to a 3rd party API in PHP which is returned to the route /api, stored in my vue.js component. Now it just logs undefined.
What documents can be apostilled/authenticated? Apostille documents.
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’,);
Solution :
fetch returns a promise containing the response res.
(This is just an HTTP response, not the actual JSON.)
To extract the JSON body content from the response, we use the json() method
You can read more about using fetch.
fetchTickets() {
fetch(‘/api’)
.then(res => res.json()) //returning a promise To extract the JSON body content from the response
.then(resJson => {
this.tickets = resJson
console.log(resJson);
})
}
Solution 2:
Return the data before going in second promise.
fetchTickets() {
fetch(‘/api’)
.then(res => {
this.tickets = res.json;
return res;
})
.then(res => {
console.log(res.json);
});
Solution 3:
add the return statement in the first promise
fetch(‘/api’)
.then(res => {
return res.json();
})
.then(tickets => {
// tickets is a local variable scoped only here
console.log(tickets);
})