reactjserror-handlingreact-functional-component

how to do error handling in react js functional components


  {    props.history.map((element,index)=>{

 return( <>
     <History temp={element.main.temp} imgvalue3={imgvalue3} imageUrl={element.weather[0].icon} mintemperature={element.main.temp_min} maxtemperature={element.main.temp_max} weather={element.weather[0].description} wind={element.wind.speed} humidity={element.main.humidity}  time={index + 1}/>
   </>
   )}
  )}

//this is the code i want to do that whenever my map function gets a null value or undefined value, i can simply show an other message like data not found.


Solution

  • a possible sollution, ternary operator. if history is null or undefined show your the h1 tag else show the history component.

    {props.history ? props.history.map((element,index)=>{
    return(<> 
     <Historyy temp={element.main.temp} imgvalue3={imgvalue3} imageUrl={element.weather[0].icon} mintemperature={element.main.temp_min} maxtemperature={element.main.temp_max} weather={element.weather[0].description} wind={element.wind.speed} humidity={element.main.humidity}  time={index + 1}/>
    </> ) }) : <h1>an error has occured</h1> }