Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS, Hooks - How to setState after .map() function?

I'm trying to change state, with values from array. Example:

const [state, setState] = useState({});
const test = [1, 2, 3];
        test.map((item, i) => {
          setState({ ...state, [`item-${i}`]: item });
        });

Current state is:

item-2: 3

What I want to achieve is:

item-0: 1,
item-1: 2,
item-2: 3

I've tried to do it in several ways (all looking similar), but the effect is the same :/ does anyone knows how to resolve it?

Thanks!

like image 526
Ola Kozioł Avatar asked Sep 15 '26 16:09

Ola Kozioł


1 Answers

You can update the state using forEach() method like:

test.forEach((item, i) => {
   setState(state => ({...state, [`item-${i}`]: item}));
});
like image 115
palaѕн Avatar answered Sep 18 '26 05:09

palaѕн



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!