Search code examples
javascriptreactjsstatedropdownuse-state

useState displays previous state when getting value from onChange event


I don't really have much experience with React but I was trying to work on a small project for myself.

So I have this dropdown list, which has 2 values, and I'm trying to console.log the current state of camera which should hold the values for the list option that you click on.

So let's say I click on an option for the 1st time, I get a log of an empty value (the initial state of my camera), then I click on the other option and I get logged the option that I clicked the 1st time. From what I understand this might be due to the fact that setState is async ?

Even so, what should I do to fix my problem, so that when I click for the first time on an option it logs the actual option ? I'm thinking of using useEffect someway but I can't really figure out how to use it for handling events. This is my code:

import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom';
import style from './Join.module.css';

const Join = () => {

    const [nume, setNume] = useState('')
    const [camera, setCamera] = useState('')


    return (
        <div className={style.mainJoinContainer}>
            <div className={style.secondaryJoinContainer}>
                <h1 className={style.header}>
                    Conecteaza-te!
                    <div>
                        <input placeholder="Nume" className={style.joinInput} type="text" onChange={(event) => { setNume(event.target.value); console.log(nume) }} />
                    </div>
                    <div className={style.margin}>
                        <label>Camera</label>
                        <select name="Camere" placeholder="Camere" onChange={(event) => { setCamera(event.target.value); console.log(camera) }}>
                            <option value="Camere" style={{ display: "none" }}>Camere</option>
                            <option value="Gluma">Gluma</option>
                            <option value="Joke">Jokes</option>
                        </select>
                    </div>
                    <Link to="/interaction/chat">
                        <button className={`${style.joinButton} ${style.margin}`} type="submit">Logheaza-te</button>
                    </Link>
                </h1>
            </div>
        </div >
    )
}

export default Join

I will appreciate any sort of guidance for this problem. I've tried looking up some similar situation and tried useEffect or async-await for some reason, but I can't really figure it out myself. Thank you for your time!


Solution

  • You can use useEffect to "watch" a state variable.

    useEffect(() => {
        // do stuff
        console.log(camera);
    }, [camera]);