So I have a React App that comunicates with my API that returns JSON data, and I want to parse that data to my results array. The problem is that axios is async, so when I execute my function, results array will be returned before it gets parsed the data from the response, and it will log as empty, so I can't use my response array in the rest of the project. How do I make the axios expression in my function to wait until it has a response and then execute the rest?
Function:
async function pin(){
const result = []
var url = "my_api_url"
axios.get(url)
.then((res)=>{
if(res.data){
result = JSON.parse(res.data.data)
}
})
console.log(result);
return result;
}
This is the react right after the function:
export default function App(){
const{isLoaded, loadError} = useLoadScript({
googleMapsApiKey: "my_api_key",
libraries,
})
const [markers, setMarkers] = React.useState([]);
if(loadError) return "Erro a carregar o mapa"
if(!isLoaded) return "Carregando"
const result = []
return <div>
{pin()}
<GoogleMap
mapContainerStyle={mapContainerStyle}
zoom={11}
center={center}
>
</GoogleMap>
</div>
}
I'm just calling the function here to see if it's OK, I haven't implemented it yet.
I have already tried to switch .then
to .await
but I get the error Objects are not valid as a React child (found: [object Promise])