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.
CodePudding user response:
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>;
})}
CodePudding user response:
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>;
})}