简体   繁体   English

返回语句给出未定义

[英]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 !任何帮助是极大的赞赏 !

Issue问题

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
}

Solution解决方案

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM