Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
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 )

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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?
    }
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!