Home > Enterprise >  How do you catch if an incoming object (from a http request) doesn't have a certain array? (Rea
How do you catch if an incoming object (from a http request) doesn't have a certain array? (Rea

Time:07-10

I'm fetching an object (with a text value and a few arrays) from an API and transferring those to local variables for use. All is working except for when that object I'm fetching doesn't have one of those arrays and I try to use it the whole site crashes. I'm lost on how to do the error handling here.

import React, { useEffect, useState } from 'react'
import classes from './Streaming.module.css'

const Streaming = (props) => {
const [streamingOn, setStreamingOn] = useState(false)
const [streamingData, setStreamingData] = useState(null)   
  
async function receiveStreaming() {
  await fetch(`https://api.themoviedb.org/3/movie/${props.movie}/watch/providers? 
api_key=35135143f12a5c114d5d09d17dfcea12`)
    .then(res => res.json())
    .then(result => {
      setStreamingData(result.results.US)   
      setStreamingOn(true)
    }, (error) => {
     console.error("Error: ", error)  
    }
     )
  
  // console.log(data)
  


}



const displayStreaming = streamingData => {   
let sortedData = { ...streamingData }

let streamData = sortedData.flatrate
let rentData = sortedData.rent

let linkText = streamingData.link

let id = Math.random()
  let streamListItems = streamData.map((movie) =>
    <li key={id}>    
      <a href={linkText}><img className={classes.logoimg} src=. {'https://image.tmdb.org/t/p/w500/'   movie.logo_path}></img></a>
    </li>) 
  let rentListItems = rentData.map((movie) =>
    <li key={id}>
 
      <a href={linkText}><img className={classes.logoimg} src={'https://image.tmdb.org/t/p/w500/'   movie.logo_path}></img></a>
    </li>)

 
return (
  <React.Fragment>
  <p>Stream on</p>
  <ul className={classes.logolist}>{streamListItems}</ul>
  <p>Rent on</p>
  <ul className={classes.logolist}>{rentListItems}</ul>
  </React.Fragment>



)

// console.log(sortedData)
}



return (
  <React.Fragment>
    <button onClick={receiveStreaming}></button>
    {<div className={classes.streaminglogos}>  
    {(streamingOn) && <div>{displayStreaming(streamingData)}</div> }
        </div>}
        </React.Fragment>
    
)

}

     export default Streaming

CodePudding user response:

Use optional chaining to check the expected array has been received or not.

Assuming that you need to show an error UI when the expected array was not received, then you can set a flag(isErrored) to true and render that conditionally.

  • Handling Response JSON
if (!result?.results?.US) {
  setIsErrored(true);
} else {
  setStreamingData(result.results.US) 
  setStreamingOn(true);
}
  • Rendering Error UI conditionally
{isErrored && (<ErrorUI />)}

CodePudding user response:

There are a few things you can do here. The first is that you could check if the array exists when you first get it and then append it on to it if it doesn't. Maybe something like:

if(!result.results.US){
    result.results.US = []
}

Or you could check if the array exists when you are displaying the data by conditionally rendering the component (or piece of component). If the data does not have the array (using the above method) don't display it.

Hope this helps!

  • Related