I don't really understand why, if I use asyn await directly to call api and I get data immediately when the component mount inside useEffect(), but when I call getLevels() from my selectApi.js, it return undefined when the component mount. See code below:
App.js
import axios from "axios";
import React, { useEffect, useState } from "react";
import { getLevels } from "./selectApi";
export default function App() {
const [options, setOptions] = useState([]);
useEffect(() => {
loadLevels();
}, []);
const loadLevels = async () => {
//Working fine if I use call await API directly in this file
const res = await axios.get("http://localhost:3040/v2/feedback/levels");
console.log("Data ----> ", res); //working fine
setOptions(res.data)
/* Not working if I import getLevels() from selectApi.js
getLevels().then((res) => {
console.log("Data --> ", res); //return Data --> Undefined when component load
});*/
};
return (
<div className="App">
<h1>Hello Select</h1>
<select>
<option value="">Please select</option>
{options.length > 0 &&
options.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
);
}
SelectApi.js
const ENDPOINT_URL = "http://localhost:3040/v2/feedback/";
export const getLevels = async () => {
await axios.get("http://localhost:3040/v2/feedback/levels");
};
Working fine when I call api directly in App.js
CodePudding user response:
Try this in selectApi.js
export const getLevels = async () => {
return await axios.get("http://localhost:3040/v2/feedback/levels");
};