Skip to content
Advertisement

Dynamically return Values from Axios-Request within function

How do I wait and/or build a return with values that come from an API-Call via axios in react?

The problem im Facing is that axios requests are asynchronous. Thats why the return from my code is hit earlier then the response from my request arrives. I’m trying to build Cards from a Weather API (openweathermap) that are returned when you enter certain parameters.

Here is how far I got. Hope you can help me:

JavaScript

Advertisement

Answer

For this use case I suggest just creating some local state representing the data you receive from the weather api. Based on this state you can then conditionally render the card body (The part of the jsx that requires to have the weather api data).

So that could look something like this:

JavaScript

The useEffect hook is used to start the axios request once after mount. If the request was successful we update the state with the data from the api. This triggers a rerender, data is defined so the card body is shown.

Conditional rendering in this example uses short-circuit evaluation, see this article for some more explanation and conditional rendering techniques in general.


Also when I tried this request out, data.weather was an array. So if you want to show the description of the first element in this array you need to do this:

JavaScript

instead of this:

JavaScript
Advertisement