API.js:54 Uncaught (in promise) TypeError: this.state.data.map is not a function
React/JavaScript newbie here. Spent all day changing my API call so it displays a loading state so the page doesn't render API data that hasn't yet been called but all I'm getting is .map() is not a function.
Could anyone give me a few pointers plesae?
const Loader = () => (
<div class="divLoader">
<svg class="svgLoader" viewBox="0 0 100 100" width="10em" height="10em">
//Loader animation
</svg>
</div>
);
class Sonos extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
data: [],
};
}
//API is called
componentDidMount() {
axios.get("API_KEY").then((res) => {
const data = res.data;
this.setState({ data: [], loading: false });
console.log(data);
});
}
render() {
return (
<div>
{this.state.loading ? <Loader /> : null}
<table border="1">
<parent>
<div className=" text-gray-700 items-center text-3xl ">
<div className="bg-gradient-to-r from-green-400 to-blue-500 min-w-full min-h-full">
<div className="text-4xl font-semibold">
{this.state.data.map((n) =>{
return (
<h1>pleasse</h1>
)
})}
</div>
</div>
</div>
</parent>
</table>
</div>
);
}
}
export { Sonos };
Solution 1:
render(){
if(this.state.loading){
return <Loader />
}
// return table if loading is false
// handling error goes with the same logic
// table will only render if loading is false
return (
<table>
</table>
)
}