score:1

Accepted answer

the selectedpokemon would be undefined untill the request to pokemon.url finishes.

and thus, initially the <pokemonmodal .../> will receive pokemon as undefined. because of which, you are seeing the error.

one way to solve it would be to have an if in the pokemonmodal component:

const pokemonmodal = ({showmodal, closemodal, pokemon}) => {
    if(pokemon && object.keys(pokemon).length !== 0) {
        // prepare the view and return it
    }
    return null;
}

you can also have an if on your parent component too, but generally speaking, i like to have the if in child component so that the parent component would not get cluttered by so many ifs

score:0

setstate is async, that's why your component is failing, as you are opening the modal, but the state might not have been set and propagated to the children yet. one way to solve this is to add a loading state to your modal.

return (
pokemon&&{
    <modal>
      <modal.title>{pokemon.name}</modal.title>
    </modal>
}

)

score:1

the reason you get a typeerror, is because you initialize your state with null, and while waiting to the response the modal tried to read the name property of pokemon. you need to handle the case when there is no pokemon set yet inside the modal, when rendering you can add const pokemonmodal = ({showmodal, closemodal, pokemon}) => { if (!pokemon) {return "loading..."}` } or some loading spinner.

no need to use json in here imho


Related Query

More Query from same tag