Skip to content
Advertisement

Axios PUT request not sending all data to server JS

My problem is that I am sending an axios request with certain data, however, not all of the data is being updated in the user model. See my code below:

Front-End code with axios request:

import axios from "axios"
import { useState } from "react"
import { useDispatch, useSelector } from "react-redux"
import { changeAddress, changeError, changeNatId, changePhone } from "../../store/contactReducer"
import { NavBar } from "../Navbar"

export const ContactInfoForm = function({nombre, correo, userId, cedula, telefono, direccion}) {
  const { natId, address, phone, error } = useSelector(({contactReducer}) => ({
    nationalid: contactReducer.nationalid,
    address: contactReducer.address,
    phone: contactReducer.phone,
    error: contactReducer.error,
  }))
  const [edit, setEdit] = useState(false)
  const dispatch = useDispatch()

  async function handleSubmit(e) {
    e.preventDefault()
    
    try {
      const { data } = await axios({
        method: 'PUT',
        baseURL: process.env.REACT_APP_SERVER_URL,
        url: `/users/user/${userId}`,
        data: {
          nationalid: natId,
          address: address,
          phone: phone,
        }
      })
      console.log(data)
    }catch(error) {
      dispatch(changeError(error))
    }
  }

  if(edit === true) {
    return(
      <>
        <NavBar />
        <form onSubmit={handleSubmit}>
          <label htmlFor='nombre'>Nombre</label>
          <p
            id='nombre'
          >
            {nombre}
          </p>
          <label htmlFor='correo'>Correo</label>
          <p
            id='correo'
          >
            {correo}
          </p>
          <label htmlFor='cedula'>Cédula</label>
          <input
            type='text'
            id='cedula'
            onChange={e => dispatch(changeNatId(e.target.value))}
          />
          <label htmlFor='direccion'>Dirección</label>
          <input
            type='text'
            id='direccion'
            onChange={e => dispatch(changeAddress(e.target.value))}
          />
          <label htmlFor='telefono'>Teléfono</label>
          <input
            type='text'
            id='telefono'
            onChange={e => dispatch(changePhone(e.target.value))}
          />
          <button
            type='submit'
            onClickC={handleSubmit}
          >
            Guardar Información
          </button>
        </form>
        <button
            type='button'
            onClick={(e) => setEdit(false)}
          >
            Cancelar
          </button>
      </>
    )
  }else if(edit === false) {
    return(
      <>
        <NavBar />
        <form>
          <label htmlFor='nombre'>Nombre</label>
          <p
            id='nombre'
          >
            {nombre}
          </p>
          <label htmlFor='correo'>Correo</label>
          <p
            id='correo'
          >
            {correo}
          </p>
          <label htmlFor='cedula'>Cédula</label>
          <p 
            id='cedula' 
          >
            {cedula}
          </p>
          <label htmlFor='direccion'>Dirección</label>
          <p 
            id='direccion'
          >
            {direccion}
          </p>
          <label htmlFor='telefono'>Teléfono</label>
          <p
            id='telefono'
          >
            {telefono}
          </p>
        </form>
        <button
            type='button'
            onClick={() => setEdit(true)}
          >
            Editar
        </button>
      </>
    )
  }
}

User model in the backend:

const { model, models, Schema } = require('mongoose')
const bcrypt = require('bcrypt') 

const userSchema = new Schema({
  email: {
    type: String,
    required: true,
    validate: {
      async validator(email) {
        try {
          const user = await models.User.findOne({ email })
          return !user
        } catch(error){
          return false
        }
      },
      message: 'El correo ya está en uso'
    },
  },
  password: {
    type: String,
    required: true,
  },
  address: {
    type: String,
  },
  phone: {
    type: String,
  },
  products: { 
    type: [{
      type: Schema.Types.ObjectId,
      ref: 'Product'
    }]
  },
  name: {
    type: String,
    required: true,
  },
  nationalid: {
    type: String,
    unique: true,
  },
  transactions: { 
    type: [{
      type: Schema.Types.ObjectId,
      ref: 'Transaction',
    }]
  },
})

userSchema.pre('save', async function() {
  if(this.password && this.isModified('password')) {
    this.password = await bcrypt.hash(this.password, 8)
  }
})

const User = model('User', userSchema)

module.exports = User

Update controller in the backend:

 async update(req, res) {
    try {
      const {body, params: {userId}} = req
      
      const user = await User.findByIdAndUpdate(userId, body, {new:true}).select('-password')
      await user.save({ validateBeforeSave: false })

      res.status(201).json(user)
      console.log(user)
    }catch(error) {
      res.status(400).json(`No se puede actualizar el usuario ${error}`)
      console.log(error)
    }

  },

Address and phone number are updating correctly, however, nationalid will not update for the life of me.

Advertisement

Answer

I found the error in my code, I forgot to change line #8 in the frontend file from const { natId, address, phone, error } to const { nationalid, address, phone, error } to match the name in the backend model.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement