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

React useState Object not getting using variable but variable-name when updating

I have a function that should update an React useState Object, but instead of the key-value the "key-name" gets inserted into the Object. What I want is to replace one value in the Object with a new one depending on the inputIndex (number between 1-4). What have I done wrong?

const [selected, setSelected] = useState({
  1:"80/static\\images\\00205.png",
  2:"80/static\\images\\00206.png",
  3:"80/static\\images\\00207.png",
  4:"80/static\\images\\00210.png"
});
const set = (inputIndex) =>{
  setSelected({...selected, inputIndex:"80/static\\images\\0001.png"})
} 

The output after the "const set" is called:

{1: '80/static\\images\\00205.png', 2: '80/static\\images\\00206.png', 3: '80/static\\images\\00207.png', 4: '80/static\\images\\00210.png', inputIndex: 'http://85.229.133.157:80/static\\images\\00210.png'}

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

>Solution :

you need to use computed property names as {[prop_name]: val}

const set = (inputIndex) =>{
  setSelected({...selected, [inputIndex]:"80/static\\images\\0001.png"})
}
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