SkyeBoniwell
SkyeBoniwell

Reputation: 7102

React function is showing that object is empty when I try to write it out to the console

I am using this constant function whenever an element in a sortable list is moved:

const arrayMoveMutate = (array, from, to) => {
    array.splice(
        to < 0 ? array.length + to : to,
        0,
        array.splice(from, 1)[0]
    );
};

const arrayMove = (array, from, to) => {
    array = array.slice();
    arrayMoveMutate(array, from, to);
    return array;
};

 const onSortEnd = React.useCallback(
        ({ oldIndex, newIndex }) => {
            setPlayer(player =>
                arrayMove(player, oldIndex, newIndex)
            );
            console.log('mock api POST to save new index positions: ', player);
            console.log('oldIndex: ', oldIndex);
            console.log('newIndex: ', newIndex);
        },
        []
    );

Here is the SortableList:

<SortableList player={player} onSortEnd={onSortEnd} />

Every time a move an element, I do see the oldIndex and newIndex in my console change.

However, 'player' is always empty.

How would I pass the 'player' object to onSortEnd so that I can do my api POST?

thanks!

Upvotes: 0

Views: 163

Answers (1)

Easwar
Easwar

Reputation: 5402

player in the console.log statement is a reference to the hook value created in your useState hook. Hence add it to the callbacks deps as below to get the fresh value, else it will always be empty within the callback :

const onSortEnd = React.useCallback(({ oldIndex, newIndex }) => {
  setPlayer(player => arrayMove(player, oldIndex, newIndex));
  console.log("mock api POST to save new index positions: ", player);
  console.log("oldIndex: ", oldIndex);
  console.log("newIndex: ", newIndex);
}, [player]);

That said, this deps is only required for logging the value inside the callback. As you are passing function to setPlayer, it will always take the latest value of the state irrespective of the deps. Hence the state should be setting fine even with your code. If still facing issues, try setting the deps and try again.

Upvotes: 2

Related Questions