How to retrieve axios data from the promise - javascript

I am currently trying to query my backend using axios and to that specific address I am sending with res.json an object and I am also able to see it with postaman. But when trying to build a function to retrieve it, my object looks like:Promise {pending}. How can i refactor my function ?
isAuthenticated = () => {
return axios.get('https://myaddress/authenticate')
.then(function (response) {
return response.data
})
};

You need to call the promise like so:
isAuthenticated().then(result => console.log(result))
.catch(error => console.log(error));

Use This code and let me know if still, you face a problem.
const isAuthenticated = () => {
return axios.get('https://myaddress/authenticate').then(response => {
// returning the data here allows the caller to get it through another .then(...)
return response.data
}).catch(error => console.log(error));
};
isAuthenticated().then(data => {
response.json({ message: 'Request received!', data })
})
here is similar questions as yours: Returning data from Axios API || Please check it as well.

Related

How to fetch data on every element in an array using array.map method

I want to fetch data for every object in an array and return an array of new objects with the previous and newly fetched data.I got stucked on getting my result array as my function is returning an array of resolved undefined promises.
I am using a flight search api thats using the apca function for fetching
export const searchApcaLocation = async (dataArr,setDeals) => {
const promises = await dataArr.map(async item => {
apca.request(item.destination);
apca.onSuccess = (data) => {
return fetch('http://localhost:3050/googlePlaceSearch',{
method:"post",
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
cityName:data.airports[0].city
})
})
.then(res => res.json())
.then(imagelinkData => {
const locationObject = {
data: item,
imagelink: imagelinkData.link
}
return locationObject
})
.catch(err => console.log('error on image search',err))
};
apca.onError = (data) => {
console.log('error',data)
};
})
const results = await Promise.all(promises)
return results
}
can someone guide me please on what am I doing wrong?
edit:
as I am trying to fix it realized the problem is I am not returning anything in my map function but if trying to return the apca.onSuccess I am getting an array of functions
just return is missing before fetch function. since you're not returning your promise result it's giving undefined.
export const searchApcaLocation = async (dataArr,setDeals) => {
const promises = await dataArr.map(async item => {
apca.request(item.destination);
apca.onSuccess = (data) => {
return fetch('http://localhost:3050/googlePlaceSearch',{
method:"post",
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
cityName:data.airports[0].city
})
})
.then(res => res.json())
.then(imagelinkData => {
const locationObject = {
data: item,
imagelink: imagelinkData.link
}
return locationObject
})
.catch(err => console.log('error on image search',err))
};
apca.onError = (data) => {
console.log('error',data)
};
})
const results = await Promise.all(promises)
return results
}
The issue in your case might be, that you are using async/await and then blocks together.
Let me sum up what is happening :
1) you await dataArray.map
2) within the map callback, you use the onSuccess method of apca
3) within this method you are using then blocks which won't await until you got a response.
At this point where you return the locationObject, your function already reached the return statement and tries to return results.
But results are of course undefined because they never get resolved at all.
Also, keep in mind that your function returns another promise because you used async/await which you have to resolve where you imported it.
Cheers :)

Return data from Promise and store it in variable after API Call

I´m pretty new to Promises and found many examples here how to access the actual value which is always done with console.log. But my goal is to store the result in a variable and work with it.
getdata = () =>
fetch(
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("This is an error");
}
})
.then(data => {
console.log(data);
});
getdata();
This code works. Can you help me to rewrite it that the getdata() function allows me to store the result in a variable. Return does not work since I will receive another pending Promise.
You can do it like this:
getdata = () =>
fetch(
"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo"
).then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("This is an error");
}
});
getdata().then(data => {
//I can do whatever with data
});
Of course you would also want to handle the scenario where the request failed, so you could also chain a .catch(). Alternately, if you have your build process configured for it, you can use async and await so you could do:
try {
const data = await getdata();
} catch(err) {
}
This would need to be in a function marked as async
Well at first we need to declare a variable let's say temp. Then use fetch API to request our query with URL. If server status is 200 then it will return a promise, we need to use then method by passing any argument (res, response, r anything...) and then a fat arrow function (=>) so that we can make the response as json format. After then we need to use another then method to return the json output and assign the value to our declared temp variable.
But if there is any error like 500, 400, 404 server error we need to use catch method with err argument and console it out.
let temp;
fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
.then(res => res.json())
.then(data => temp = data)
.catch(err => console.log(err));

Fetch res.json() Attempt to invoke intergace method 'java.lang.String...'

I'm trying to convert a response from fetch function into json format but when I do so I get an error Attempt to invoke interface method 'java.lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang.String)' on a null object reference.
Here is my code snippet with fetch function:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res))
})
}
If comment back the row with console.warn I see the following "res keys = type, status, ok, statusText, headers, url, _bodyInit, _bodyBlod, bodyUsed".
bodyUsed = false
status = 200
type = default
Why I can't convert a response into json format? Or is there any another way to do so?
UPDATE
I've added the second then but I still get the error and the console.warn('res is json') is not running:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res));
})
.then(res => {
console.warn('res is json');
console.warn(res);
})
}
UPDATE_2
I've run fetch function with another url but still got the problem. It seems like .json() causes the error. When I'm trying to console the result of fetch in the first .then() I get json object with type, status etc keys.
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
//.then(res => res.json())
.then(json => console.warn('JSON: ' + json))
.catch(e => console.warn('ERROR: ' + e))
}
UPDATE_3
Forgot to mention that I'm creating an Android app with React Native. For testing I'm using a physical smartphone. Chrome version there is 73.0.3683.
I've replaced my fetch query with the following:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
But still get the same error.
When I run it in https://jsfiddle.net/ it works. So the reason is hidden inside the code execution on a smartphone.
There must be more context to your problem; see the below snippet. This clearly works.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));

Console log undefined after fetching api in Vue

When fetching from an API (3rd party, I authenticate and get the data in my Laravel Controller) I get 'undefined' in the console. I want to store the data in a Vue 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 I am 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 I want 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 component. Now it just logs undefined.
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',);
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);
})
}
Return your data before going in second promise.
fetchTickets() {
fetch('/api')
.then(res => {
this.tickets = res.json;
return res;
})
.then(res => {
console.log(res.json);
});
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);
})

Chain React setState callbacks

I need to load three different json files in an ordered sequence and with a fetch (the reason is i'm using nextjs export and i need those files to be read dynamically, so I fetch them when needed and their content can change even after the export)
The first file contains data that is used to create the url for the second file and so on, so each fetch needs an actually updated state to be fetched,
ATM the solution i'm using, since the second and third files are dependent from the first and second respectively, is fetching the first file and setting some state with setState, then in the setState callback fetch the second file and set some other state and so on:
fetch(baseUrl).then(
response => response.json()
).then(
res => {
this.setState({
...
}, () => {
fetch(anotherUrl+dataFromUpdatedState).then(
response => response.json()
).then(
res => {
this.setState({
...
}, () => {
fetch(anotherUrl+dataFromUpdatedState).then(
response => response.json()
).then(
res => {
this.setState({
})
}
)
})
}
).catch(
error => {
//error handling
}
)
})
}
).catch(
error => {
this.setState({ //an error occured, fallback to default
market: defaultMarket,
language: defaultLanguage,
questions: defaultQuestions
})
//this.setLanguage();
}
)
Now: I know that setState must be used carefully as it is async, but as far as I know the callback function is called after state is updated so from that point of view the state should update correctly. Is this solution anti-pattern, bad practice or should be avoided for some reason?
The code actually works, but i'm not sure if this is the way to do it.
You don't need to use the setState callback and read it from the state, since you can just read the data directly from the res object. This way you can make a flat promise chain.
Example
fetch(baseUrl)
.then(response => response.json())
.then(res => {
this.setState({
// ...
});
return fetch(anotherUrl + dataFromRes);
})
.then(response => response.json())
.then(res => {
this.setState({
// ...
});
return fetch(anotherUrl + dataFromRes);
})
.then(response => response.json())
.then(res => {
this.setState({
// ...
});
})
.catch(error => {
this.setState({
market: defaultMarket,
language: defaultLanguage,
questions: defaultQuestions
});
});

Categories

Resources