Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: How to properly append multiple items to an array state using its use-state hook setter?

My component has a state that should store an array of objects. I initialized it to be empty.

    const [tableDataSource, setTableDataSource] = useState([])

After a couple successful fetching and reorganizing of fetch results, one or more object literals should be appended to the tableDataSource state. Desired output should be

[
    {
        key: 1,
        key2: 'sample string value',
        key3: false,
    },
    {
        key: 'sample string value',
        key2: true,
    }
]

My current fetch result is another array containing 2 object literals. I tried to append all items from this array to the state setter.

    let dataSource = generateRows(showCompletedItems, fetchResult);

The code above reorganizes the fetch results into desired output. I logged dataSource in the console and verified if it is an Array object and it returned true.

Somewhere inside the component declaration I also have a useEffect that logs the current tableDataSource to output the changes.

    console.log('TABLE DATA SOURCE >>>>', tableDataSource, typeof tableDataSource);

I have a difficult time appending the array items into the state array using its setter. I tried Approach # 1:

    setTableDataSource(dataSource);

The console does not log anything.

Approach # 2:

    setTableDataSource((tableDataSource) => [...tableDataSource, dataSource])

Returns a nested array as shown below:

    [[{...},{...}]]

If I used Approach # 2 and initialized the component state like this:

    const [tableDataSource, setTableDataSource] = useState([{}])

Result:

    [{}, [{...}, {...}]]

Approach # 3 does not log anything like the first one

    setTableDataSource((tableDataSource) => [...tableDataSource, ...dataSource])
like image 771
migsm Avatar asked Dec 30 '25 13:12

migsm


2 Answers

Figured it out.

setArrayOfObjects((currentObjects) => currentObjects.concat([ ...anotherArrayOfObjects]))

I hope this very specific problem will help others. It was very annoying, it took me hours to figure it out.

like image 103
migsm Avatar answered Jan 01 '26 09:01

migsm


You can use Set.

setTableDataSource((tableDataSource) => [... new Set([...tableDataSource, ...dataSource])])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

like image 37
aksal Avatar answered Jan 01 '26 08:01

aksal



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!