Karan Sharma
Karan Sharma

Reputation: 1

I am getting this error "Cannot read properties of undefined (reading 'map')" when i use map method in my react app

when I use the map method inside the showData function it works, but when I use it while rendering, it shows an error.

export class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      word: "",
      data: [],
    };
  }

  handelWordChange = (e) => {
    this.setState({ word: e.target.value });
  };

  showData = async () => {
    
    let url = `https://api.urbandictionary.com/v0/define?term=${this.state.word}`;
    let rawData = await fetch(url);
    let parsedData = await rawData.json();
    this.setState({ data: parsedData });

    this.state.data.list.map((e) => {
      console.log(e.definition);
    });
  };

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handelWordChange}
        />
        <button onClick={this.showData}>Show</button>

        {this.state.data.list.map((e) => {
          return <h1>{e.definition}</h1>;
        })}
      </div>
    );
  }
}
 

I am learning to react and I came through this error can anyone please help me out.

Upvotes: -1

Views: 96

Answers (2)

Mohsin Baig
Mohsin Baig

Reputation: 87

This Error is appearing because when your component load on the first render then your data variable value is an empty array, Add the conditional check before applying the map on the array.

{this.state.data && this.state.data.list && this.state.data.list.map((e) => {
      return <h1>{e.definition}</h1>;
})}

Upvotes: 2

Tushar Shahi
Tushar Shahi

Reputation: 20701

This error is when you are accessing properties/indices from something undefined.

Use optional chaining to make sure you are only accessing properties of objects which themselves are defined.

{this.state.data.list?.map((e) => {
          return <h1>{e.definition}</h1>;
        })}

Upvotes: 0

Related Questions