Home > Mobile >  ReactJS TypeError: Cannot read properties of undefined (reading 'main')
ReactJS TypeError: Cannot read properties of undefined (reading 'main')

Time:10-19

I am trying to make the weather app in React JS , but when I run the program I get the error "TypeError: Cannot read properties of undefined (reading 'main')". Below is part of the code:

 return (
 <div className={(typeof weather.main != "undefined") ? ((weather.main.temp > 16 ) ? 
 'app warm':'app'):'app'}>
   <main>

   <div className="search-box">

     <input type='text' 
      className='search-bar' 
      placeholder='Search ...'
      onChange={e => setQuery(e.target.value)}
      value={query}
      onKeyPress={search}
      />
    </div>
    
    {(typeof weather.main != "undefined") ? (
     <div>
      <div className='location-box'>
      <div className='location'>{weather.name}, {weather.sys.country}</div>
      <div className='date'>
        {dateBuilder(new Date())}
      </div>
      </div>
      <div className='weather-box'>
      <div className='temp'>
      {Math.round(weather.main.temp)}
      </div>
      <div className='weather'>
      {weather.weather[0].main}
      </div>
    
      </div>
     </div>
    ): (' ')}
  </main>
   </div>
  );
  }

CodePudding user response:

weather is undefined at some point. Since you are only checking if weather.main is undefined or not, at some point your code tries to read field main of undefined.

One solution may be conditional chaining. Try changing

(typeof weather.main != "undefined") ? ...

to

weather?.main && (...

Full code

return (
 <div className={`app ${weather?.main?.temp > 16 ? 'app warm':''}`}>
   <main>

   <div className="search-box">

     <input type='text' 
      className='search-bar' 
      placeholder='Search ...'
      onChange={e => setQuery(e.target.value)}
      value={query}
      onKeyPress={search}
      />
    </div>
    
    {weather?.main && (
     <div>
      <div className='location-box'>
      <div className='location'>{weather.name}, {weather.sys.country}</div>
      <div className='date'>
        {dateBuilder(new Date())}
      </div>
      </div>
      <div className='weather-box'>
      <div className='temp'>
      {Math.round(weather.main.temp)}
      </div>
      <div className='weather'>
      {weather.weather[0].main}
      </div>
    
      </div>
     </div>
    ): (' ')}
  </main>
   </div>
  );
  }
  • Related