简体   繁体   English

处理 axios.get 中的错误和 react/js 中收到的数据

[英]Handle error in axios.get and data received in react/js

I'm struggling to figure out how to prevent my app from crashing after fetching data from an API.我正在努力弄清楚如何防止我的应用在从 API 获取数据后崩溃。 Here's what I have done so far:这是我到目前为止所做的:

User searches for a word and based on that word, the program goes to a link with the searched phrase, then fetches and stores data in a const用户搜索一个词,并基于该词,程序转到搜索短语的链接,然后获取数据并将其存储在 const

var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=****`;

${search} = whatever the user enters in the searchbar ${search} = 用户在搜索栏中输入的任何内容

then baseUrl is the webite used to get all the data from API然后 baseUrl 是用于从 API 获取所有数据的网站

  useEffect(() => {
      axios.get(baseUrl)
      .then(res => {
        setChart(res.data);
        // console.log(res.data)
      })
      .catch(error => {
        console.log("there was an error: " + error);
      })
  }, [baseUrl]);

   useEffect(()=>{}, [chart]);

then the program loops thru the API and stores DATE and PRICE for each entry in const stockPrices and stockDates .然后程序循环通过 API 并将 DATE 和 PRICE 存储在 const stockPricesstockDates中的每个条目。

      const stockPrices = useMemo(() => chart && Object.values(chart['Time Series (Daily)']).map(i => i['1. open']).reverse(), [chart]); 
      const stockDates = useMemo(() => chart && Object.keys(chart['Time Series (Daily)']).map(x => x.replace(/\d{4}-/, "")).reverse(), [chart]);

However, sometimes if user enter a search for which there's no existing link.. the app crashes, as it's trying to loop and display data that doesn't exist.但是,有时如果用户输入一个没有现有链接的搜索......应用程序崩溃,因为它试图循环和显示不存在的数据。

I'm not really sure how to handle this.我不确定如何处理这个问题。

In the search component, I added this little "if" statement to stop it doing anything if the search is empty ( because no such link exists ):在搜索组件中,我添加了这个小“if”语句来阻止它在搜索为空时执行任何操作(因为不存在这样的链接):

  const handleSearch = (e) => {
    e.preventDefault();
    if (e.target.value !== ``) {
    setSearch(e.target.value.toUpperCase())
    }};

However, this only solves a small part of the problem.然而,这只解决了一小部分问题。 If the app tries to fetch data from an invalid link it simply crashes.如果应用程序尝试从无效链接获取数据,它只会崩溃。

when the app crashes - in the console it says "Cannot convert undefined or null to object" which is reported from the line where const stockPrices and const stockDates are sitting on.当应用程序崩溃时 - 在控制台中它显示“无法将未定义或 null 转换为对象”,这是从const stockPricesconst stockDates所在的行报告的。

How can I stop the app from fetching data if a link doesn't exist - how to handle this bug ?如果链接不存在,如何阻止应用程序获取数据 - 如何处理此错误?

just for context the data stored in those variables is then passed to render a chart with prices (Y-axis) and dates(X-axis) so it needs to at least have some sort of replacement..仅出于上下文考虑,然后将存储在这些变量中的数据传递给带有价格(Y 轴)和日期(X 轴)的图表,因此它至少需要进行某种替换。

if(typeof stockDates === 'undefined') {
    return ('undefined');
} else if(stockDates=== null){
    return ('null');
} 

I tried doing this to replace bad fetch with 'null' ||我尝试这样做以用'null'替换错误的提取|| 'undefined' but it's still crashing. '未定义',但它仍然崩溃。

Please help.请帮忙。

IN SHORT : App crashes if it's trying to fetch data from a link that doesn't exist ( based on input from searchbar )简而言之:如果应用程序尝试从不存在的链接获取数据(基于搜索栏的输入),应用程序会崩溃

I'm not sure what error you're facing with the search problem.我不确定您在搜索问题时遇到了什么错误。

The other one's the error you get when you pass undefined to Object.keys or Object.values function.另一个是将undefined传递给Object.keysObject.values函数时出现的错误。

I'm gonna guess the API returns some data for invalid links so chart is not undefined.我猜API会返回一些无效链接的数据,所以图表不是未定义的。 In the code, you're checking to make sure chart is not undefined.在代码中,您正在检查以确保chart未定义。 But most likely, chart['Time Series (Daily)'] is undefined.但最有可能的是, chart['Time Series (Daily)']未定义。

I don't know enough about your requirements to suggest a fix.我对您的要求知之甚少,无法提出修复建议。 But you could add an additional check and make it so...但是你可以添加一个额外的检查并使它......

const stockPrices = useMemo(() => chart && chart['Time Series (Daily)'] && Object.values(chart['Time Series (Daily)']).map(i => i['1. open']).reverse(), [chart]); 
const stockDates = useMemo(() => chart && chart['Time Series (Daily)'] && Object.keys(chart['Time Series (Daily)']).map(x => x.replace(/\d{4}-/, "")).reverse(), [chart]);

But I think it'd be better to fix the fetch code.但我认为修复获取代码会更好。

axios.get(baseUrl)
.then(res => {
    if (res.data?.['Time Series (Daily)']) {
        setChart(res.data);
    }
    else {
        setChart(undefined);
        //maybe set some error states so you can display the appropriate message?
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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