HTTP ( PUT request) is not working using axios in React.js

I’m performing a CRUD operation by adding data in db.json server file.
My edit request is not working like I’m using a Class component and having Error ::

App.js

import React, { useState, useEffect } from 'react';
import {BrowserRouter as Router, Switch,Route} from 'react-router-dom'
import axios from 'axios';
import Header from './components/header';
import DisplayList from './components/displayList';
import InputForm from './components/InputForm';
import EditContacts from './components/editContacts';
import './App.css';

function App() {
  const [contacts,setContacts] = useState([]);

  const getContacts = async ()=>{
    try{
      const res = await axios.get("http://localhost:4000/contacts");
      setContacts(res.data)
    } 
    catch(err){
      console.log(err);
    }
  }

  const addingContacts = async (contact)=>{
    const request = {...contact}
    const response = await axios.post("http://localhost:4000/contacts",request)
    setContacts([...contacts,response.data]);
  }

  const removeContacts = async(id) =>{
   await axios.delete(`http://localhost:4000/contacts/${id}`);
  const newContacts = contacts.filter(contact=> contact.id !== id);
    setContacts(newContacts);
  }
 
//Edit and Update function:
  const updatingContacts = async(contact)=>{
   const response = await 
      axios.put(`http://localhost:4000/contacts/${contact.id}`,contact);
    const {id,Username,Email} = response.data;
    console.log(response.data); 
    setContacts(contacts.map(contact=>{
      return contact.id !== id ? {...response.data} :contact
    }))
  }
  useEffect(()=>{
    getContacts();
  },[])
  
  return (
    <Router>
      <Switch>
        <div className="App">
          <Route path="/" exact>
          <Header/>
          </Route>
          <Route path="/add">
          <InputForm addingContacts={addingContacts}/>
          </Route>
          <Route path="/diplay">
          <DisplayList  contacts={contacts} removeContacts={removeContacts}/>
          </Route>

          <Route path="/edit">
          <EditContacts updatingContacts={updatingContacts}/>
          </Route>
        </div>
      </Switch>
    </Router>
  );
}

export default App;

(editContact.js)Edit Component:

import React, { Component } from 'react';
import{Link} from 'react-router-dom';
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";

class editContacts extends Component {
    constructor(props) {
        super(props)
       const {id,Username,Email} = props.location.state.contact
        this.state = {
             id,
             Username,
             Email
        }
    }
    handleUpdate=(e)=>{
        e.preventDefault();
        if(!this.state.Username  && !this.state.Email){
            return alert("Input Fields are Empty");
        }
        else{
            alert(`My name is: ${this.state.Username} and my Email address is: ${this.state.Email}`);
        }
        this.props.updatingContacts(this.state);
        this.setState({Username:"",Email:""})
    }
    
    render() {
        return (
            <div>
            <div className="card" >
                 <div className="card-header text-center">
                 <h2>Add Contacts</h2>
                </div>
            </div>
            <Form onSubmit={this.handleUpdate}>
                
            <Form.Group className="mb-3" controlId="formBasicName">
                    <Form.Label>Name</Form.Label>
                    <Form.Control type="text" placeholder="Name" name="Username"value ={this.props.state.Username} onChange={(e)=>{this.setState({Username:e.target.value})}}/>
                </Form.Group>

                <Form.Group className="mb-3" controlId="formBasicEmail">
                    <Form.Label>Email address</Form.Label>
                    <Form.Control type="email" placeholder="Enter email" name="Email" value ={this.props.state.Email} onChange={(e)=>{this.setState({Email:e.target.value})}}/>
                </Form.Group>

                <Button variant="btn btn-outline-success" type="submit" style={{marginBottom:"20px", marginRight:"8px"}}>
                    Update
                </Button>
                <Link to="/">
                <Button variant="btn btn-outline-secondary" type="button" style={{marginBottom:"20px"}}>
                    Main Page
                </Button>
                </Link>
            </Form>
                
            </div>
        )
    }
}

export default editContacts

“Error is occuring in Edit component” Please lemme know if anyone understand this error.

I’m assuming the error occurs when you simply navigate to /edit, is that correct?

Yes !! when I click on edit button then this error occurs:

And here is the code from where list get displayed:

import React from 'react';
import { Link } from 'react-router-dom';

const  displayList = (props) => {
    
    const  delContact=(id)=>{
        props.removeContacts(id);
        alert("Item is successfully removed");
    }
 
const returnList = props.contacts.map((contact,index)=>{
    return (
        <> 
            <tr>
                <th>{index+1}</th>
                <td>{contact.Username}</td>
                <td>{contact.Email}</td>
                <td>
                <Link to={{pathname:"/edit", state:{contact:props.contact}}}>
                <button className="btn btn-outline-primary" style={{ marginRight: "7px" }}><i className="bi bi-pencil-square"></i></button>
                </Link>
                <button className="btn btn-outline-danger" onClick={()=>delContact(contact.id)}><i className="bi bi-trash-fill"></i></button>
                </td>
            </tr>
          
        </>
        );
    });

    return (
    <div>
       <div className="card" >
        <div className="card-header text-center">
          <h2>Contact List</h2>
        </div>
      </div>
        <table className="table table-border table-bordered table-striped text-center">
        <thead>
            <tr>
            <th>#</th>
            <th>Name</th>
            <th>Email</th>
            <th>Action</th>
            </tr>
        </thead>
          <tbody>{returnList}</tbody>
        </table>
        <Link to="/">
        <button className="btn btn-outline-secondary">Main Page</button>
        </Link>
    </div>
       
)
}

export default displayList

   const {id,Username,Email} = props.location.state.contact

I don’t think props.location is available there like that.

So what supposed I should do ? then ? cause I don’t getting the error

When you browse to /edit/, App.js renders editContacts.js and passes updatingContacts as the only props to the component.
updatingContacts is a function defined in App.js that takes a contact object, updates it on the backend and sets the state to represent the new state of the contacts.
But in your editContacts.js page, you are looking for a location property in props, which you never passed in. So, location is undefined and it has no state property, as the image of the error you provided shows.

Hope that helps

1 Like

So in App.js in this line:
You are passing down the function definition of updatingContacts.
UpdatingContacts is accepting one argument which is “contact”.
So pass contact down into editContact from App.js .

@JasonCorp84 Like how ??

Billy, I don’t mean this to be offensive in anyway, but I think you may lack some react fundamentals. Without them, trying to debug this problem will be in vain.

Have you completed FCC’s frontend development certification with all its projects? If so, have you implemented those projects in react?
I’m asking because, if not, that’s where to start to methodically solve this problem.

https://www.freecodecamp.org/learn/front-end-libraries/react/pass-props-to-a-stateless-functional-component and everything below.

Also, I would suggest doing the Todo app from Reactjs.org to clear up these questions.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.