User1267
User1267

Reputation: 7

Fetching the value on dropdown change in React

I have the following code. Initially, when I select 2022 I don't see the value logged in the console, and also if I select 2021 then '2022' gets logged in the console. I also tried changing the initial state to 2022 by

I tried the below code,

const [selecteddropdown,setdropdown] = useState(2022);

but still, the selected value is not getting printed. What do I need to change?

const Filter = () => {
  const [selecteddropdown,setdropdown] = useState('');
  const handleChange = (event) => {
    setdropdown(event.target.value);
    console.log(selecteddropdown);
  };

  return (
    <div className='expenses-filter'>
      <div className='expenses-filter__control'>
        <label>Filter by year</label>
        <select value={selecteddropdown}  onChange={handleChange}>
          <option value='2022'>2022</option>
          <option value='2021'>2021</option>
          <option value='2020'>2020</option>
          <option value='2019'>2019</option>
        </select>
      </div>
    </div>
  );
};

Upvotes: 0

Views: 615

Answers (2)

thug_
thug_

Reputation: 1093

What you actually see in your log is previously selected value. If you follow reference from @Yoshi comment you can get better understand why that is the case.

To fix it, remove your console.log in handleChange method and instead call it in the block of code from below then you will see actual value of your selecteddropdown.

  useEffect(() => {
    console.log(selecteddropdown);
  }, [selecteddropdown]);

useEffect() hook fires in this case wheneever selecteddropdown state is upaded.

Upvotes: 2

Calix
Calix

Reputation: 356

Even if you change the state (selecteddropdown) of the setState, the code line below still shows the state value before it was changed, so this is the right situation. If you want another action after that, you have to develop it with this in mind.

Upvotes: 0

Related Questions