I am new to React and am running through a tutorial that uses the Poke API (https://pokeapi.co).
I am using whatwg-fetch to make requests to the API. This saves data from the API as an object to the state 'selectedPokemon'.
this.state = {
// other states
showModal: false,
selectedPokemon: null
};
I want to send that data to a component (in my case a modal), so I updated my modal component call to include the selectedPokemon state as a prop:
<PokemonModal pokemon={this.state.selectedPokemon} closeModal={this.handleModalClose} showModal={this.state.showModal} />
I also updated my PokemonModal component (on PokemonModal.js) to include pokemon as a prop:
const PokemonModal = ({showModal, closeModal, pokemon}) => {
However, when I go to use that prop within PokemonModal, eg:
<Modal.Title>{pokemon.name}</Modal.Title>
I get an error
Uncaught TypeError: Cannot read property 'name' of null
(This is the same with any other part of the object I try to use eg pokemon.order. The showModal and closeModal props work as expected.)
Would anyone know how I could send and use a JSON object to another component?
If it matters, my fetch function is set up as such. The console.log returns the expected result, which is the object from: https://pokeapi.co/api/v2/pokemon/10125/
handleModalOpen(pokemon) {
if(pokemon.url !== undefined) {
fetch(`${pokemon.url}`)
.then(response => {
return response.json();
})
.then(json => {
this.setState({
selectedPokemon: json,
showModal: true
})
console.log('selected: ' + this.state.selectedPokemon);
})
.catch(ex => {
console.log('pasrsing failed ' + ex);
})
}
}