0

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

        }]
}
1

1 Answer 1

2

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]})
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.