for(const extra of fruit?.extras) {
const [extra.label'Count', 'set'extra.label'Count'] = useState();
};
Obviously this doesn't work at all, but I want to do something like this to map each array item to its own useState hook.
CodePudding user response:
Do you have any trouble with using an array in useState()?
When you want to change an item in the array, create a new Array and add all the items to it. Then change that one item you want to change and pass that to set function. Example:
function App() {
const [state, setState] = useState([{ value: 1}, { value: 2 }]);
const onChange = (newValue, index) => {
setState(prevState => {
const temp = [...prevState];
temp[index].value = newValue;
return temp;
});
}
return <div>
{state.map((item, index) => <button key={index} onClick={() => onChange(item.value 1, index)}>{item.value}</button>)}
</div>
}
CodePudding user response:
You cannot use hooks inside a loop. Hooks always use at the top level of your React function.