Reputation: 19
I am trying to do an ajax call using fetch. The database is ran through mongo and when using dummy data from a .json file, the map works correctly when decks: [], it gives the error.
class Home extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
decks: []
};
}
componentDidMount() {
fetch("/api/getAllDecks")
.then(
(result) => {
this.setState({
isLoaded: true,
decks: result.decks
});
console.log("hiiii");
},
(error) => {
this.setState({
isLoaded: true,
error
});
console.log('hryyyy');
})
}
render() {
const decks = this.state.decks;
return (
<div className='container'>
{this.state.decks.map(decks => (
<MiniCard
word={decks.deckName}
/>
))};
</div>
);
};
}
Upvotes: 0
Views: 676
Reputation: 12018
With the Fetch API, you need to transform the response into the kind of data you want in order to use it. To do that here, call .json()
on the response object returned from the fetch call.
fetch('/api/getAllDecks')
.then(response => response.json())
.then(data => {
this.setState({ isLoaded: true, decks: data.decks })
})
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Also, won't hurt to double check to make sure that data.decks
is correct by doing a console.log
on it.
Upvotes: 1
Reputation: 197
Short circut this.state.decks
{
this.state.decks &&
this.state.decks.map { decks => (<MiniCard word={decks.deckName} />))
};
Upvotes: 0