skip to Main Content

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


  1. You should return the value when you set it:

    const handleObjectSelect = (selectedObject) => {
     // Checks if movie choices were a match
     setUserChoices((prevChoices) => {
        const updatedChoices = [...prevChoices, selectedObject];
        return updatedChoices; //This line should be added.
     });
    };
    
    Login or Signup to reply.
  2. You almost had it!
    You forgot to return state in your function.

    setUserChoices((prevChoices) => {
            const updatedChoices = [...prevChoices, selectedObject];
            return updatedChoices; 
    
    Login or Signup to reply.
  3. as others have pointed out, you just have a small syntax error, the short hand syntax would look like this:

    setUserChoices((prevChoices) =>  [...prevChoices, selectedObject]);
    

    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!

    const handleObjectSelect = (selectedObject) => {
     if (selectedObject === userChoice) {
       // Success case
     }  else {
       setUserChoice(selectedObject);
     {
    }; 
    

    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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search