Reputation: 15
I am trying to update a state array after accepting the input from Form. State already has events object in it with data and I want to accept data from the form and append to the existing list. I'm able to do console log of the newEvents (data from form in another component), but using the spread operator unable to update the existing state by appending it.
//getting newEvent object from form in another component. // events is an array in state which has data //priniting the existing array without appending newEvent //printing data from form (newEvent) properly
testmethodfornow = (newEvent) => (
{ ...this.state.events, events: [newEvent, ...this.state.events] },
console.log(this.state.events),
console.log(newEvent)
)
I want newEvent to be added to event :( Can anyone please help ?
NewEvent structure:
const newEvent = { IdText: uuid(), EventName, Venue, Time };
events array structure in state:
state = {
flag: false,
title: "State Check",
events: [
{
IdText: '1',
EventName: 'New Year Party 2022',
Venue: 'The Social',
Time: '8:00 PM- 1:00AM',
Date: ''
},
{
IdText: '2',
EventName: 'StandUp Comedy',
Venue: 'ShilpaRamam',
Time: '8:00 PM- 1:00AM',
Date: ''
}]
}
Upvotes: 0
Views: 2800
Reputation: 153
If you are using class components, use setState
to update the state. In this case events
is a field of the state. So you can spread rest of the state
instead of state.events
.
addNewEvent(){
setState({...this.state, events: [newEvent, ...this.state.events]})
}
Upvotes: 2