I apologize but I could not find an answer that helps with my problem.
I'm making a pokemon 20 questions game and recently added a new question to ask.
I'll do my best to keep it clear. But every answer is stored in state
Like this:
const [type, setType] = useState(null);
const [weakness, setWeakness] = useState(null);
const [evolve, setEvolve] = useState(null);
etc.
So I have buttons set up that assign these values as a user progresses through the game. But my evolve question breaks the game.
Here is the function
const evolveAssign = (canEvolveBoolean) => {
setEvolve(canEvolveBoolean);
setPokemonData((prevPokeArray) => // pokemon data is a giant array of pokemon objects
prevPokeArray.filter((pokemon) => {
if (canEvolveBoolean === true) {
return pokemon.prev_evolution || pokemon.next_evolution; //checks if the properties exist. Pokemon that do not evolve, do not have such properties.
} else {
return !pokemon.prev_evolution && !pokemon.next_evolution;
}
})
)};
This is how it is being returned. Which I admit, I'm not sure if this is the best way to display questions.
{type && weakness && !evolve && (
<div>
<strong>Can your Pokemon Evolve?</strong>
<EvolveBtn mapEvolutions={mapEvolutions} onClick={evolveAssign} />
</div>
)}
The problem
When the user hits 'No' it will pass false
to the function, and it does seem to work! But the question gets stuck only on "No" So I logged
<p>evolve = {evolve}</p>
and it will show 'evolve = '. So somehow, evolve is not being set at all? I haven't had this issue before with the other questions.
Is there something weird going on because it's a Boolean? Is my JS logic bad? I'm pretty much out of ideas. I apologize if this was unclear/messy. I'd love any feedback as I'm still learning.
Thank you very much.
EDIT: Created a Codesandbox here!
https://codesandbox.io/s/damp-bush-u6yel?file=/src/App.js
The error can be seen if you choose Bug -> Fire -> "No". It will break after that.
CodePudding user response:
I took a look at the sandbox. Several things can be improved but I will just focus on the evolve
issue.
In JavaScript null
and false
are falsy values. !null
or !false
will return true
. This is why the questions are rendered incorrectly after selecting evolve
.
A quick and easy fix would be to check if evolve
is null
or the opposite if the user already selected evolve
.
{
type && weakness && (evolve === null) && (
<div style={{ fontSize: 50 }}>
<strong>Can your Pokemon Evolve?</strong>
<EvolveBtn mapEvolutions={mapEvolutions} onClick={evolveAssign} />
</div>
)
}
{/* What height? */ }
{
type && weakness && (evolve !== null) && !height && (
<div style={{ fontSize: 50 }}>
<strong>Select Height</strong>
<HeightBtn mapHeight={mapHeight} onClick={heightAssign} />
</div>
)
}
Similar checks need to be used in the rest of the conditions if you simply want to make the app work.