I have fetched the below data from an API but out of 10 objects 1 object has multiple properties assigned to NULL. API fetched data screenshot
While rendering these objects with properties it is throwing an error of "cannot read properties of NULL(reading ‘value’)" . Here is my code:
const Home = () => {
const [movies, setMovies] =useState([]);
useEffect(()=>{
const fetchData =async()=>{
try{
const {data} = await axios.get("https://api.tvmaze.com/search/shows?q=all")
setMovies(data)
console.log(data)
}
catch{
}
}
fetchData()
},[])
return (
<div className="movieCards-container ">
<h1 className="heading"> Recommended Movies</h1>
<div className=" container-custom d-flex align-items-center justify-content-center pb-5 ">
<div className="row justify-content-center">
{movies.map((item,index) => {
return (
<div className=" col-12 col-md-6 col-lg-4 d-flex align-items-center justify-content-center ">
<MovieCard
key={item.show.id}
id={item.show.id}
name={item.show.name}
image={item.show.image.original}
rating={item.show.rating.average}
showday={item.show.schedule.days}
showtime={item.show.schedule.time}
/>
</div>
);
})}
</div>
</div>
</div>
)
}
I want to render all other objects except the one with properties assigned to NULL.
2
Answers
You need to perform a conditional render of the component.
So just do:
Of course it’s still better to do optional chaining everywhere to prevent this sort of error in case a single field is missing ex. item?.show?.id
I think all you need is to use ternary operator.
Link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator
This way you can conditionally send the parameter to your component.
You check first if something exists, and if it does exist. Use it. If not send a placeholder for example.
Example:
{item.show.image ? item.show.image.original : ‘placeholder’}
Here I check if the "item.show.image" exists. If it does I use the "item.show.image.original". If not. I render "placeholder".
I hope it will help you. 🙂