简体   繁体   中英

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. 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

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

${search} = whatever the user enters in the searchbar

then baseUrl is the webite used to get all the data from 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 .

      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 ):

  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.

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..

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

I tried doing this to replace bad fetch with '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.

I'm gonna guess the API returns some data for invalid links so chart is not undefined. In the code, you're checking to make sure chart is not undefined. But most likely, chart['Time Series (Daily)'] is undefined.

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?
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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