I am trying to parse data from my Web API and show it on my react page, the connection is successful and the data is parsed (I can see an array of elements in the console) but whenever I want to show it on the page I get this error:
TypeError: Cannot read property 'map' of undefined.
I am using axios for the connection so here is my code:
import React from 'react';
import axios from 'axios';
class Player extends React.Component {
state = {
loading: true,
error: "",
data: []
};
loadData = () => {
this.setState({ loading: true });
return axios
.get('http://localhost:6444/api/example')
.then(result => {
console.log(result);
this.setState({
data: result.data.items,
loading: false,
error: false
});
})
.catch(error => {
console.error("error: ", error);
this.setState({
error: `${error}`,
loading: false
});
});
};
componentDidMount() {
this.loadData();
}
render() {
const { loading, error, data } = this.state;
if (loading) {
return <p>Loading ...</p>;
}
if (error) {
return (
<p>
There was an error loading the players.{" "}
<button onClick={this.loadData}>Try again</button>
</p>
);
}
return (
<div>
<h1>Players</h1>
<p>{data.map((player, index) => {
return (
<div key={index} player={player}></div>
)})}</p>
</div>
);
}
}
export default Player;
I hope anyone can help me figure out the problem, I tried many things by now but nothing fixed the problem.
result.data.items
is not returned in your response. You might want to tryresult.data.items || []
or add an error if it's empty. – Acidic9console.log(result)
? – Mukesh Soniconsole.log(result);
? – Prerak Solaresult.data.items
also a non-empty array? – Prerak Sola