[英]Return statement giving undefined
I am having a function: fetchAll
which is in the fetch.js
file.我有一个 function: fetchAll
,它在fetch.js
文件中。
import axios from "../axios";
export default function fetchAll() {
axios.get("/api/videos/all").then((response) => {
return response.data;
});
}
Then in Home.js
:然后在Home.js
中:
import fetchAll from "../functions/fetch";
useEffect(() => {
var videos = fetchAll();
console.log(videos);
},[])
But the function returns undefined
instead of the data.但是 function 返回undefined
而不是数据。
Any help is greatly appreciated !任何帮助是极大的赞赏 !
You are not returning anything from fetchAll
function.您没有从fetchAll
function 返回任何内容。
export default function fetchAll() {
axios.get("/api/videos/all").then((response) => {
return response.data;
});
// <-- no return, void return
}
Return the Promise from axios
从 axios 返回axios
export default function fetchAll() {
return axios.get("/api/videos/all").then((response) => {
return response.data;
});
}
You will, of course, need to wait for the Promise to resolve in the useEffect
callback.当然,您需要等待 Promise 在useEffect
回调中解析。
useEffect(() => {
const getFetchAll = async () => {
try {
const videos = await fetchAll();
console.log(videos);
} catch(err) {
console.error(err);
}
}
getFetchAll();
},[]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.