Malloc28
Malloc28

Reputation: 97

How do I map each array item to a useState hook?

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.

Upvotes: 1

Views: 963

Answers (2)

Dinesh
Dinesh

Reputation: 162

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>
}

Upvotes: 1

engineercc
engineercc

Reputation: 1

You cannot use hooks inside a loop. Hooks always use at the top level of your React function.

Upvotes: 0

Related Questions