Home > Software design >  How can I edit using MySQL , NodeJs, React Js,
How can I edit using MySQL , NodeJs, React Js,

Time:07-22

I've been trying to figure this out for hours, but i think im doing it wrong. So what im basically doing is.

-> Fetch the specific user, and throw it into the placeholder -> which is working

but when I try to edit the information and then when i try to save it this error shows and then in my phpadmin, it saves a null. it seems that I can't connect the front and the backend.

sql: 'UPDATE users SET name = NULL, email = NULL, mobile = NULL WHERE id = ${id} '

Edit.jsx

import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'

const EditUser = () => {
  const navigate = useNavigate()
  const [data, setData] = useState([])
  const [inputs, setInputs] = useState([])
  const { id } = useParams()

  useEffect(() => {
    const getUser = async () => {
      const res = await axios.get(`http://localhost:5000/${id}`)
      setData(res.data[0])
    }
    getUser()
  }, [])

  const handleSubmit = async () => {
    try {
      await axios.put(`http://localhost:5000/${id}`, inputs)
    } catch (error) {
      console.log(error)
    }
  }

  const handleChange = (e) => {
    setInputs({ ...inputs, [e.target.name]: e.target.value })
  }

  return (
    <div>
      <form
        action=""
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'column',
        }}
        onSubmit={handleSubmit}
      >
        <label htmlFor="">Name</label>
        <input type="text" placeholder={data.name} onChange={handleChange} />
        <label htmlFor="">Email</label>
        <input type="text" placeholder={data.email} onChange={handleChange} />
        <label htmlFor="">Mobile</label>
        <input type="text" placeholder={data.mobile} onChange={handleChange} />
        <button type="submit">save</button>
      </form>
    </div>
  )
}

export default EditUser

backend.js

app.put('/:id', (req, res) => {
  const id = req.params.id
  const name = req.body.name
  const email = req.body.email
  const mobile = req.body.mobile
  pool.query(
    `UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,

    [name, email, mobile],
    (err, result) => {
      if (err) {
        console.log(err)
      } else {
        res.send(result)
      }
    }
  )
})

app.get('/:id', (req, res) => {
  const { name, email, mobile } = req.body
  const { id } = req.params

  pool.query(`SELECT * FROM users WHERE id = ${id} `, (err, result) => {
    if (err) {
      console.log(err)
    } else {
      res.send(result)
    }
  })
})

enter image description here

CodePudding user response:

May be you should try :

The following states :

const EditUser = () => {

 const navigate = useNavigate()
 const [data, setData] = useState([])
 const [name, setName] = useState("")
 const [email, setEmail] = useState("")
 const [mobile, setMobile] = useState("")
 const { id } = useParams()

For your request :

const handleSubmit = async () => {
    let datas ={
      name: name,
      email: email,
      mobile: mobile
    }
    try {
      await axios.put('http://localhost:5000/updateUser/' id, datas)
    } catch (error) {
      console.log(error)
    }
  }

Then you just update your states that way :

      <form
    action=""
    style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'column',
    }}
    onSubmit={handleSubmit}
  >
    <label htmlFor="">Name</label>
    <input type="text" placeholder={data.name} onChange={()=> 
    {setName(e.currentTarget.value)} />
    <label htmlFor="">Email</label>
    <input type="text" placeholder={data.email} onChange={()=> 
    {setEmail(e.currentTarget.value)} />
    <label htmlFor="">Mobile</label>
    <input type="text" placeholder={data.mobile} onChange={()=> 
    {setMobile(e.currentTarget.value)} />
    <button type="submit">save</button>
  </form>

For you back end maybe you should add some informations in the adress (to avoid confusion with you app.get):

app.put('updateUser/:id', (req, res) => {
 const id = req.params.id
 const name = req.body.name
 const email = req.body.email
 const mobile = req.body.mobile
 pool.query(
  `UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,

  [name, email, mobile],
(err, result) => {
  if (err) {
    console.log(err)
  } else {
    res.send(result)
  }
}

) })

I hope it will help you !

CodePudding user response:

I think I did it actually, but I dont know if this is the right method. so what i did is

instead of directing submit it as an await

 const handleSubmit = async () => {
    try {
      await axios.put(`http://localhost:5000/${id}`, inputs)
    } catch (error) {
      console.log(error)
    }
  }

i did this.

const handleSubmit = async (e) => {
e.preventDefault()
try {
  const res = await axios.put(`http://localhost:5000/${id}`, inputs)
  setInputs(res.data)
} catch (error) {
  console.log(error)
}}

Hey guys, if its wrong, please show me the other way.

  • Related