Home > Enterprise >  React JS cannot Update the record
React JS cannot Update the record

Time:12-11

i have create the simple crud system in React with Laravel. i shall be able to add the records and view the records but couldn't update the records. what i tried so far i attached below. i attached the full code for easy for understanding. i think the problem is occur in the update url is there any error. Api i tested through the console it is working well in update part

i attached the when i looked at the console

    127.0.0.1:8000/api/update/undefined:1 
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

Full code

import axios from 'axios';
import {useEffect, useState } from "react";

    function EmployeeLoad()
    {
      const [id, setId] = useState('');
      const [name, setName] = useState("");
      const [address, setAddress] = useState("");
      const [mobile, setMobile] = useState("");
    
    
    const [users, setUsers] = useState([]);
    
    useEffect(()=>
    {
      Load();
    },[])
    
    
    
    
      async function  Load()
      {
         const result = await axios.get(
             "http://127.0.0.1:8000/api/employees");
             setUsers(result.data);
             console.log(result.data);
      }
     
        
         async function save(event)
        {
            event.preventDefault();
        try
            {
             await axios.post("http://127.0.0.1:8000/api/save",
            {
            
              name: name,
              address: address,
              mobile: mobile
            
            });
              alert("Employee Registation Successfully");
              setId("");
              setName("");
              setAddress("");
              setMobile("");
            
            
            }
        catch(err)
            {
              alert("User Registation Failed");
            }
       }
       async function editEmployee(users)
       {
        setName(users.name);
        setAddress(users.address);
        setMobile(users.mobile); 
     
        setId(users.id);
        
       }
    
    
       async function update(event)
       {
        event.preventDefault();
    
       try
           {
            
            await axios.patch("http://127.0.0.1:8000/api/update/"  users.id,
           {
             id: id,
             name: name,
             address: address,
             mobile: mobile
           
           });
             alert("Employee Registation Successfully");
             setId("");
             setName("");
             setAddress("");
             setMobile("");
           
           
           }
       catch(err)
           {
             alert("User Registation Failed");
           }
      }
    
    
      return (
        <div>
           <h1>Employee Details</h1>
           <div  >
              <form>
                  <div >
                   <input  type="text"  id="employee_id" 
                   value={id}
                   onChange={(event) =>
                    {
                      setId(event.target.value);      
                    }}
                   
                   />
                    <label>employeeName</label>
                    <input  type="text"  id="employeeName"
                    value={name}
                    onChange={(event) =>
                      {
                        setName(event.target.value);      
                      }}
                    />
                  </div>
                  <div >
                    <label>employeeAddress</label>
                    <input  type="text"  id="employeeAddress" 
                     value={address}
                      onChange={(event) =>
                        {
                          setAddress(event.target.value);      
                        }}
                    />
                  </div>
    
                  <div >
                    <label>Mobile</label>
                    <input type="text"  id="employeeMobile" 
                      value={mobile}
                    onChange={(event) =>
                      {
                        setMobile(event.target.value);      
                      }}
                    />
                  </div>
    
                     <div>
                  <button     onClick={save}>Register</button>
                  <button     onClick={update}>Update</button>
                  </div>   
                </form>
              </div>
    
    <table  align="center">
      <thead>
        <tr>
          <th scope="col">Employee Id</th>
          <th scope="col">Employee Name</th>
          <th scope="col">Employee Address</th>
          <th scope="col">Employee Mobile</th>
          
          <th scope="col">Option</th>
        </tr>
      </thead>
           {users.map(function fn(item)
           {
                return(
                <tbody>
                    <tr>
                    <th scope="row">{item.id} </th>
                    <td>{item.name}</td>
                    <td>{item.address}</td>
                    <td>{item.mobile}</td> 
                  
                    <td>
                    
    
    
    
                        <button type="button"   onClick={() => editEmployee(item)} >Edit</button>)}    
                        <button type="button"  >Delete </button>
                    </td>
    
    
                    </tr>
                </tbody>
                );
                })}
                </table>
                    </div>
                );
            }
     
    export default EmployeeLoad;

while Running the code this error displayed

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

CodePudding user response:

There's no users.id and that's why the dynamically-constructed path is wrong and the API rejects it. http://127.0.0.1:8000/api/update/undefined

The error is thrown because of this line:

await axios.patch("http://127.0.0.1:8000/api/update/"  users.id,
           {
             id: id,
             name: name,
             address: address,
             mobile: mobile
           });

You can try to await the call to the Load function in the useEffect.

Also, try adding if (!users) {return null;}

before the main JSX return.

I think there's something wrong with what your API returns.

Check what the users variable contains.

Something like:

import axios from 'axios';
import {useEffect, useState } from "react";

function EmployeeLoad()
{
  const [id, setId] = useState('');
  const [name, setName] = useState("");
  const [address, setAddress] = useState("");
  const [mobile, setMobile] = useState("");


const [users, setUsers] = useState([]);

useEffect(async ()=>
{
  await Load();
},[])




  async function  Load()
  {
     const result = await axios.get(
         "http://127.0.0.1:8000/api/employees");
         setUsers(result.data);
         console.log(result.data);
  }
 
    
     async function save(event)
    {
        event.preventDefault();
    try
        {
         await axios.post("http://127.0.0.1:8000/api/save",
        {
        
          name: name,
          address: address,
          mobile: mobile
        
        });
          alert("Employee Registation Successfully");
          setId("");
          setName("");
          setAddress("");
          setMobile("");
        
        
        }
    catch(err)
        {
          alert("User Registation Failed");
        }
   }
   async function editEmployee(users)
   {
    setName(users.name);
    setAddress(users.address);
    setMobile(users.mobile); 
 
    setId(users.id);
    
   }


   async function update(event)
   {
    event.preventDefault();

   try
       {

        console.log('Let Aifos Si Prahs know what is here', users);
        
        await axios.patch("http://127.0.0.1:8000/api/update/"  users.find(u => u.id === id).id || id,
       {
         id: id,
         name: name,
         address: address,
         mobile: mobile
       
       });
         alert("Employee Registation Successfully");
         setId("");
         setName("");
         setAddress("");
         setMobile("");
       
       
       }
   catch(err)
       {
         alert("User Registation Failed");
       }
  }


  if (users.length <= 0) return null;

  return (
    <div>
       <h1>Employee Details</h1>
       <div  >
          <form>
              <div >
               <input  type="text"  id="employee_id" 
               value={id}
               onChange={(event) =>
                {
                  setId(event.target.value);      
                }}
               
               />
                <label>employeeName</label>
                <input  type="text"  id="employeeName"
                value={name}
                onChange={(event) =>
                  {
                    setName(event.target.value);      
                  }}
                />
              </div>
              <div >
                <label>employeeAddress</label>
                <input  type="text"  id="employeeAddress" 
                 value={address}
                  onChange={(event) =>
                    {
                      setAddress(event.target.value);      
                    }}
                />
              </div>

              <div >
                <label>Mobile</label>
                <input type="text"  id="employeeMobile" 
                  value={mobile}
                onChange={(event) =>
                  {
                    setMobile(event.target.value);      
                  }}
                />
              </div>

                 <div>
              <button     onClick={save}>Register</button>
              <button     onClick={update}>Update</button>
              </div>   
            </form>
          </div>

<table  align="center">
  <thead>
    <tr>
      <th scope="col">Employee Id</th>
      <th scope="col">Employee Name</th>
      <th scope="col">Employee Address</th>
      <th scope="col">Employee Mobile</th>
      
      <th scope="col">Option</th>
    </tr>
  </thead>
       {users.map(function fn(item)
       {
            return(
            <tbody>
                <tr>
                <th scope="row">{item.id} </th>
                <td>{item.name}</td>
                <td>{item.address}</td>
                <td>{item.mobile}</td> 
              
                <td>
                



                    <button type="button"   onClick={() => editEmployee(item)} >Edit</button>)}    
                    <button type="button"  >Delete </button>
                </td>


                </tr>
            </tbody>
            );
            })}
            </table>
                </div>
            );
        }
 
export default EmployeeLoad;

Althoug this won't help if your users object doesn't contain an id.

CodePudding user response:

Please Read Request not work in web but works on postman

There's some policy that applied on browser, but not on postman or insomnia or other api testing tool. you must apply some config on your web server or make some change in api.

Also for laravel project, maybe Method not allowed in laravel is helpful.

  • Related