Home > Software engineering >  How to use spread operator or use prev state in React Native
How to use spread operator or use prev state in React Native

Time:03-04

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']

CodePudding user response:

The initial state should be an array. Change {} to []

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

CodePudding user response:

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([]);
  • Related