Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change of state render previous state React

I’m trying to change the state of a component but it keep rendering the previous state.

From what I understood, the component is rendered before the state is getting saved and I need to use a callback function, except that I did not succeed.

Here is a simplified code of what I’m trying to do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function ColorPick() {

  const [color, setColor] = useState('');
  const [choice, setChoice] = useState('blue');

   const handleColor = (event, newChoice) => {
    setChoice(newChoice)
    if(choice === 'blue'){
      setColor('blue')
    }else{
      setColor('red') 
    }
  };

  return (
    <select onChange={handleColor} value={choice}>
     <option value="red">Red</option>
     <option value="blue">Blue</option>
    </select>
    <h1>{color}</h1>
  );
}

Thank you

>Solution :

You can just use the event parameter which returns the selected value. Then your handleColor will look like this

const handleColor = (event) => {
  console.log(event.target.value);

  if (event.target.value === "blue") {
    setColor("blue");
  } else {
    setColor("red");
  }
};

  <select onChange={handleColor}>
    <option value="red">Red</option>
    <option value="blue">Blue</option>
  </select>
  <h1>{color}</h1>

Then also you don’t need to use the choice state

Codesandbox example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading