'How to use spread operator or use prev state in React Native

When I press a button it should call a function and send data. I am using spread operator so that I can keep the prev data. The problem is that my starting state is {} and when I console.log the data I see that I have empty object in my data

const [prevState, setState] = React.useState({});


const handleBtnPress =(info)=>{
setState(prevState => [...prevState, info] );

}

console.log(prevState)

output:

[{}, 'some data', 'for each button press']

output I am hoping for

['some data', 'for each button press']


Solution 1:[1]

You are using using an object as initial state. And your expected output is an Array. Hence you should set initial state to an Array. Your code should be :

const [prevState, setState] = React.useState([]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Madhan S