Reputation: 63
I am trying to import a function that fetches data from an api in a file (.src/api/index.js) to my App.js (.src/App.js).
.src/api/index.js
import axios from 'axios';
const url = 'https://covid19.mathdro.id/api';
export const fetchData = async () => {
try {
const res = await axios.get(url);
return res;
} catch (error) {}
};
.src/App.js
import React, { useEffect } from 'react';
import { fetchData } from './api';
const App = () => {
useEffect(() => {
const data = fetchData();
console.log(data);
}, []);
return <div></div>;
};
export default App;
};
I am getting a Promise{<pending>}
in my console when I run this but I am trying to get the values in the object.
Upvotes: 1
Views: 1521
Reputation: 2587
You are not waiting for promise to resolve. use await or .then. If you wanna use await, make callback function of useEffect async function.
const App = () => {
useEffect(async () => {
const data = await fetchData();
console.log(data);
}, []);
return <div></div>;
};
Other approach is to use .then.
const App = () => {
useEffect(async () => {
const data = fetchData().then((data) => console.log(data));
}, []);
return <div></div>;
};
Upvotes: 1
Reputation: 2154
fetchData()
is an async function, and you need to await
it like so:
const data = await fetchData();
Then, the useEffect
must also be an async function:
useEffect(async () => {
const data = await fetchData();
console.log(data);
}, []);
Upvotes: 1