Is assigning a value to a property of a const object supposed produce a typeError?

55 Views Asked by At

const sendData = result => {
    result.centers.forEach(center => {
        const data = {
            center_id,
            name,
            address,
            district_name,
            state_name,
            pincode,
            fee_type,
            sessions
        } = center ;
        data.sessions = data.sessions.map(session => {
            return {
                date,
                available_capacity,
                min_age_limit,
                vaccine
            } = session ;
        })
        console.log(data) ;
    })
}

why does the above code produce the following error ?

PS: Please ignore the line numbers.

UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
    at /home/ubuntu/Projects/Web/CowinTracker/server/app.js:69:17
    at Array.map (<anonymous>)
    at /home/ubuntu/Projects/Web/CowinTracker/server/app.js:67:39
    at Array.forEach (<anonymous>)
    at sendData (/home/ubuntu/Projects/Web/CowinTracker/server/app.js:56:20)

I tried changing const data to let data and same error occurred.

1

There are 1 best solutions below

3
On BEST ANSWER

You can't destructure in your return statement.

You need to either destructure the session argument, or reference the session object and assign the properties to a new object.

const data = {
  centers: [
    {
      center_id: 1,
      name: 'One',
      address: '1 one street',
      district_name: 'one',
      state_name: 'one',
      pincode: '1111',
      fee_type: 1,
      sessions: [
        {
          date: new Date(),
          available_capacity: 1,
          min_age_limit: 1,
          vaccine: "its gene therapy"
        }
      ]
    }
  ]
}


const sendData = result => {
    result.centers.forEach(center => {
        const data = {
            center_id,
            name,
            address,
            district_name,
            state_name,
            pincode,
            fee_type,
            sessions
        } = center ;
        data.sessions = data.sessions.map(session => {
            return {
                date: session.date,
                available_capacity: session.available_capacity,
                min_age_limit: session.min_age_limit,
                vaccine: session.vaccine
            } ;
        })
        console.log(data) ;
    })
}

sendData(data)

If you wanted to destructure the session argument you could do something like this.

data.sessions = data.sessions.map((( 
  date, 
  available_capacity,
  min_age_limit,
  vaccine,
}) => ({
    date,
    available_capacity,
    min_age_limit,
    vaccine,
}) 

})

If you're just cloning the object you could do the following.

data.sessions = data.sessions.map(session => ({
  ...session
}))