Search code examples
mysqlreactjsfetchundefinedreact-props

Incorrect Integer value: 'undefined' for column 'user_id'


I am a bit confused here as I'm trying to submit a post, however, it gives me 'user_id' 'undefined, but if I console.log I see that the integer is 12. I've been trying many different things in the last two days, without success and I am not able to see the problem here (please, bear in mind that I am a beginner in coding).

This is the route:

routes.post("/profile/share", (req, res) => {
    let { user_id, body, createdAt, updatedAt } = req.body;
    
    db(`INSERT INTO shares (user_id, body, createdAt, updatedAt) 
        VALUES ('${user_id}', '${body}', '${createdAt}', '${updatedAt}'); 
        `)
        .then(results => {
            if(!results.error) {
                res.status(201).send({})
            }
            res.send(results)
        })
        .catch(err => res.status(500).send(err))
})

This is the function in my component:

handleSubmit = event => {
      event.preventDefault()
      const { user_id } = this.props.user[0].id
      console.log(this.props.user[0].id)
      const { body, createdAt, updatedAt } = this.state
          axios.post("http://localhost:7001/api/profile/share", {
            data: {
              user_id,
              body,
              createdAt,
              updatedAt
            }
          }) 
          .then(response => {
            console.log(response.data)
            this.setState(state => ({
              loggedIn: !state.loggedIn,
            }))
          })
          .catch(error => {
            console.log(error)
          })
    }

This is the console: enter image description here

And the message from error 500:

enter image description here

Does anyone spot where my error is? Any help will be much appreciated.

Thank you in advance.


Solution

  • As per the console log this.props.user[0].id is a number. You shouldn't destructure it, instead, you can directly assign it to a variable and use it.

    As you are destructuring, the user_id is going as undefined that is causing the issue.

    const { user_id } = this.props.user[0].id;  This should be change to
    
    const user_id = this.props.user[0].id;
    

    Pass the params like below:-

    axios.post("http://localhost:7001/api/profile/share", {
                  user_id,
                  body,
                  createdAt,
                  updatedAt
              })