Creating a React app where the user chooses 2 movies out of 5 options and if the movies are the same it returns Success. I attempted to store the choices made in state and then compare them, it returns the Success correctly but when a second movie is clicked after the first one it says the choices array is empty again.
So if I click movie1 and then click movie2 and then click movie1 a second time it will say success as if its storing each movie clicked in its own separate array
I’ve tried many variations but this is the general code I have:
const [userChoices, setUserChoices] = useState([]);
useEffect(() => {
if (userChoices.length === 2) {
console.log(userChoices)
if (userChoices[0] === userChoices[1]) {
console.log('W');
} else {
console.log('L');
}
}
}, [userChoices]);
const handleObjectSelect = (selectedObject) => {
// Checks if movie choices were a match
setUserChoices((prevChoices) => {
const updatedChoices = [...prevChoices, selectedObject];
});
};
return <div className="content-card" onClick={() => handleObjectSelect(movie?.title)}>
<img className="movie-poster img-fluid" src={`${img500x500}/${movie?.poster_path}`} />
<div className="movie-title">{movie?.title}</div>
<div className="movie-info">
<span>{movie?.release_date}</span>
<span><FontAwesomeIcon icon={faStar} />{movie?.vote_average}</span>
</div>
</div>;
I also tried storing the choices in a regular array and a regular variable but the same problem persists, I’m new to react and would appreciate any help thanks!
3
Answers
You should return the value when you set it:
You almost had it!
You forgot to return state in your function.
as others have pointed out, you just have a small syntax error, the short hand syntax would look like this:
One small suggestion is that you probably don’t need an array or even
useEffect
to achieve this. If you think about it, just a simple string is good enough. You set the string to be empty initially, then, before you set it to a new string, compare it to the old string first and see if they match!My last tip would be to look into how to setup and use Typescript. I know it’s gonna be quite challenging learning Typescript but it will help you catch almost 99% of these syntax issues. Good luck!