Search code examples
javascriptreactjsobjectjsxdestructuring

React "cannot destructure property"


So i am trying to learn React and i am following a tutorial, i follow along and the i do everything as in the tutorial, the person saves the changes and it compiles, but mine gives out this error: TypeError: Cannot destructure property 'text' of 'seasonConfig[season]' as it is undefined.

Here is the component i am trying to render:

import React from 'react';

const seasonConfig = {
  summer: {
    text: '',
    iconName: 'sun'
  },
  winter: {
    text: '',
    iconName: 'snowflake'
  }
};

const getSeason = (lat, month) => {
  if (month > 2 && month < 9) {
    return lat > 0 ? 'summer ' : 'winter';
  } else {
    return lat > 0 ? 'winter ' : 'summer';
  }
};

const SeasonDisplay = (props) => {
  const season = getSeason(props.lat, new Date().getMonth());
  const { text, iconName } = seasonConfig[season];

  return (
    <div>
      <i className={` massive ${iconName} icon`} />
      <h1>{text}</h1>
      <i className={` massive ${iconName} icon`} />
    </div>
  );
};

export default SeasonDisplay;

Solution

  • Remove the space after summer and winter in the if conditions:

    const getSeason = (lat, month) => {
      if (month > 2 && month < 9) {
        return lat > 0 ? 'summer' : 'winter'; // 'summer ' => 'summer'
      } else {
        return lat > 0 ? 'winter' : 'summer'; // 'winter ' => 'winter'
      }
    };
    

    OR if we really need the space, could also do seasonConfig[season.trim()].