Home > Enterprise >  Uncaught TypeError: Cannot read properties of undefined (reading 'params') in a MERN Stack
Uncaught TypeError: Cannot read properties of undefined (reading 'params') in a MERN Stack

Time:05-01

I was working on a MERN stack app that could perform CRUD operations. But the update doesn't seem to work. While performing an update operation I can see the updated values in the browser console but it doesn't seem to update the values in the database and keep getting an error which I stated above in the title. Thanks in advance.

import React, {Component} from 'react';
import axios from 'axios';
import Sidebar from '../../components/sidebar/Sidebar';
import Navbar  from '../../components/navbar/Navbar';
import "./dbtrial.scss";

export default class DrUpd extends Component{
  constructor(props){
    super(props);
    this.onChangeName= this.onChangeName.bind(this);
    this.onChangeEmail = this.onChangeEmail.bind(this);
    this.onChangePhone = this.onChangePhone.bind(this);
    this.onChangeAddress= this.onChangeAddress.bind(this);
    this.onChangeCountry= this.onChangeCountry.bind(this);
    this.onSubmit = this.onSubmit.bind(this)
    this.state = {
      name: '',
      email: '',
      phone: '',
      address: '',
      country: '',
      driver:[]
    }
  }
  
  componentDidMount(){
    axios.get('http://localhost:3001/driver/getDrivers')
    .then(response =>{
        this.setState({
            //driver: response.data
            name: response.data.name,
            email: response.data.email,
            phone: response.data.phone,
            address: response.data.address,
            country: response.data.country
        })
        .catch((error) =>{
            console.log(error);
        })
    })
}
  onChangeName(e){
    this.setState({
      name: e.target.value
    })
  }
  onChangeEmail(e){
    this.setState({
      email: e.target.value
    })
  }
  onChangePhone(e){
    this.setState({
      phone: e.target.value
    })
  }
  onChangeAddress(e){
    this.setState({
      address: e.target.value
    })
  }
  onChangeCountry(e){
    this.setState({
      country: e.target.value
    })
  }
  onSubmit(e){
    e.preventDefault();
    const driver={
      name: this.state.name,
      email: this.state.email,
      phone: this.state.phone,
      address:this.state.address,
      country: this.state.country
    }
    console.log(driver)
    axios.post('http://localhost:3001/driver/update/:id' this.props.match.params.id,driver )
    .then(res => console.log(res.data))
    .catch((error) =>{
      console.log(error);
  })
    
   
  }
  render(){
    return(
      <div className="db">
            <Sidebar />
            <div className="dbq">
              <Navbar />
              <h3>Edit Driver</h3>
              <form onSubmit={this.onSubmit}>
                  <div className="formInput">
                    <label>Name:</label>
                    <input type="text"
                    required
                    
                    value={this.state.name}
                    onChange={this.onChangeName}
                    />
                  </div>
                  <div className="formInput">
                    <label>Email:</label>
                    <input type="email"
                    required
                    
                    value={this.state.email}
                    onChange={this.onChangeEmail}
                    />
                  </div>
                  <div className="formInput">
                    <label>Phone:</label>
                    <input type="text"
                    required
                    
                    value={this.state.phone}
                    onChange={this.onChangePhone}
                    />
                  </div>
                  <div className="formInput">
                    <label>Address:</label>
                    <input type="text"
                    required
                    
                    value={this.state.address}
                    onChange={this.onChangeAddress}
                    />
                  </div>
                  <div className="formInput">
                    <label>Country:</label>
                    <input type="text"
                    required
                    
                    value={this.state.country}
                    onChange={this.onChangeCountry}
                    />
                  </div>
                  <div className="formInput">
                    
                  <input type="submit" value="Edit Driver" onSubmit={() => this.onSubmit()}  />
                  </div>
              </form>
            </div>
      </div> 
    )
  }
}

router.route('/update/:id').post((req, res) => {
    Driver.findById(req.params.id)
      .then(driver => {
        driver.name = req.body.name;
        driver.email = req.body.email;
        driver.phone = req.body.phone;
        driver.address = req.body.address;
        driver.country =req.body.country;
        
        driver.save()
          .then(() => res.json('Driver updated!'))
          .catch(err => res.status(400).json('Error: '   err));
      })
      .catch(err => res.status(400).json('Error: '   err));
  });

CodePudding user response:

In your frontend you're fetching the following url:

axios.post('http://localhost:3001/driver/update/:id' this.props.match.params.id,driver )

But what your URL should be is:

axios.post('http://localhost:3001/driver/update/' this.props.match.params.id,driver)

This way this.props.match.params is used an :id, the first case you're sending ':id' as id instead of match.params, and then your backend

Driver.findById(req.params.id) //req.params.id = ':id' in your case

CodePudding user response:

Try by removing:id in post methods like this

if your get an error in the frontend don't initialize the:id route component

<Route path={"/yourpath/:id"} component ={yourcomponent}/> 

if you get error on the backend .

axios.post('http://localhost:3001/driver/update/' this.props.match.params.id,driver )
.then(res => console.log(res.data))
.catch((error) =>{
  console.log(error)})

Because in the route you defined params as id so you don't specify in the post method URL. Also, use async-await every time you update setState and like async componentDidMount () and use await like await this.setState({yourState}). if you use await don't forget to use async before the function.

Thanks.

  • Related