I'm using react hooks and I need to dynamically change the hook based on the loop's i value. I feel like there's a simple way to do it but can't find where. Any help is appreciated, thank you.
const [hanzi0, setHanzi0] = useState(0);
const [hanzi1, setHanzi1] = useState(0);
const [hanzi2, setHanzi2] = useState(0);
const [hanzi3, setHanzi3] = useState(0);
for(var i = 0; i < 4; i++) {
setHanzi0(tmpData[x].hanzi);
}
You cannot dynamically look up a local variable name. It's just not a feature that javascript has.
But what you can do is look up a value in some data structure. Like, say, an array.
const [hanzis, setHanzis] = useState([0,0,0,0])
Now you can update that state like this:
const newHanzis = [...hanzis] // create a shallow copy of the array
for(var i = 0; i < 4; i++) {
newHanzis[i] = tmpData[i].hanzi
}
setHanzis(newHanzis)
If you need to dynamically access different states, then you don't actually have different states, you have one state that has enough complexity to hold many pieces of data.
for(var i = 0; i < 4; i++) {
if(i === 0) setHanzi0(tmpData[x].hanzi0);
if(i === 1) setHanzi1(tmpData[x].hanzi1);
if(i === 2) setHanzi2(tmpData[x].hanzi2);
if(i === 3) setHanzi3(tmpData[x].hanzi3);
}