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'}
CodePudding user response:
you need to use computed property names as {[prop_name]: val}
const set = (inputIndex) =>{
setSelected({...selected, [inputIndex]:"80/static\\images\\0001.png"})
}