Home > other >  api response returned in javascript returning undefined unless i do &&
api response returned in javascript returning undefined unless i do &&

Time:12-04

I am using react and there seems to be an issue with the loadtime of the api. Like lets say I am trying to get

<div>{movieInfo.full_name}</div>

which is one of the fields being returned. If I were to do the above, it would throw an error

However, if I did the following it would work

{ movieInfo && <div>{movieInfo.full_name}</div>}

This can be pretty inefficient and messy if I had to do this for all other fields being returned from that endpoint. Think has something to do with race condition. Is there any way I can combat this? Thanks!

CodePudding user response:

you can do this for example:

{
  movieInfo ? 
(
  <>
    <div>{movieInfo.full_name}</div>
    <div>{movieInfo.year}</div>
  </>
) : Loader
}

or if still it looks messy you can create variable and check if movieInfo exist then you display data like this:

let movies = <Loader />
if(movieInfo) {
   movies = (
     <>
       <div>{movieInfo.full_name}</div>
       <div>{movieInfo.year}</div>
    </>
 )
}
return movies

CodePudding user response:

You can change the code to this:

  <div>{movieInfo?.full_name}</div>

If this doesn't work, you can do something like this:

 if (!movieInfo) return <LoadingIndicator />

 return (
    <div>{movieInfo.full_name}</div>
 );

You can return null or a loading idicator like a spinner if movieInfo is not yet loaded.

  • Related