0

I have an object which I have created in state and it is my model for the booking. My addPassenger function should when click create an empty object into array with properties. When I console.log the new array it returns me the array properly but when I execute function nothing happens, no error. Just blank console.

My whole component https://pastebin.com/RLprKJrr

 booking: {
        id: "",
        number: "",
        date: "",
        bookingStatus: "OPCIJA",
        paymentMethod: "MODELA1",
        tripID: 1,
        passengers: [
          {
            id: "",
            holder: {
              email: "",
              address: "",
              mobile: ""
            },
            name: "",
            surname: "",
            passport: "",
            idCard: ""
          }
        ]
      }

addPassenger = e => {
    e.preventDefault();
    let passengersArray = [...this.state.booking.passengers];
    console.log(passengersArray);
    this.setState({
      passengers: [...passengersArray, {
        id: "", 
        name: "",
        surname: "",
        passport: "",
        idCard: ""
      }]
    })
    this.checkArrayLength();
  }

squizyt
  • 31
  • 1
  • 11

3 Answers3

0

Because the problem is with data being passed to setState

This is the structure of your initial state

{
  booking: {
    passengers: {
      ...
    }
  }
}

Which is then accessible through this.state.booking.passengers

But when you are setting state again, you are putting passengers on same level as bookings like this

{
   booking: {
     ...
   },
   passengers: {
     ...
   }
 }

So you basically need to do this

this.setState({
  bookings: {
    ...this.state.bookings,
    passengers: [...passengersArray, {
        id: "", 
        name: "",
        surname: "",
        passport: "",
        idCard: ""
      }]
  }
})
Umair Abid
  • 1,453
  • 2
  • 18
  • 35
  • I understand what you mean but when I place it like that it returns me unexpected token. Here is the image https://imgur.com/a/OPSiAJR – squizyt Mar 26 '19 at 14:37
  • Ok thanks for the tip i found the solution, It was the typo and I had to store `...this.state.bookings` to const and use it in setState, setState obviously doesnt like storing in properties like that. – squizyt Mar 26 '19 at 14:40
0

Please try to set state of booking.passengers, not just passengers:

this.setState({
  booking.passengers: ...
Roman
  • 456
  • 3
  • 4
0

You have to include the key 'booking' in your new state:

this.setState(previousState => ({
  booking: {
    ...previousState.booking,
    passengers: [...passengersArray, {
      id: "", 
      name: "",
      surname: "",
      passport: "",
      idCard: ""
    }]
  }
}));

I hope it helps you!

Jose Ramos
  • 673
  • 3
  • 10
  • Ok at the end I was missing this https://stackoverflow.com/questions/38490804/spread-operator-in-react-throwing-error-of-unexpected-token/38490899 – squizyt Mar 27 '19 at 09:28