Home > other >  reactjs "TypeError: Cannot read properties of undefined (reading 'params')"
reactjs "TypeError: Cannot read properties of undefined (reading 'params')"

Time:07-22

I'am new using reactjs and looks like I am following the old tutorial with old version of react router. So the objectives is when I want to edit the user detail, the form must be filled with data of previous user before update. I've already comunicate with the backend using axios and it worked fine, but the problem is in "id = props.match.params.id". and here is my code:

UserEdit.tsx

import axios from "axios";
import React, { SyntheticEvent, useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import Wrapper from "../../components/Wrapper";
import { Role } from "../../models/role";

const UserEdit = (props: any) => {
    const [first_name, setFirstName] = useState('');
    const [last_name, setLastName] = useState('');
    const [email, setEmail] = useState('');
    const [role_id, setRoleId] = useState('');
    const [roles, setRoles] = useState([]);
    const [redirect, setRedirect] = useState(false);
    let id: number;


    useEffect(() => {
        (
            async () => {
                const response = await axios.get('roles');

                setRoles(response.data);

                id = props.match.params.id;

                const {data} = await axios.get(`users/${id}`);

                setFirstName(data.first_name);
                setLastName(data.last_name);
                setEmail(data.email);
                setRoleId(data.role_id);
            }
        )()
    }, []);

    const submit = async (e: SyntheticEvent) => {
        e.preventDefault();

        await axios.put('users', {
            first_name,
            last_name,
            email,
            role_id
        });

        setRedirect(true)
    }

    if(redirect) {
        return <Navigate to="/users"/>
    }

    return (
        <Wrapper>
            <form onSubmit={submit}>
                <h1 className="h3 mb-3 fw-normal">Edit user</h1>
                <div className="form-floating">
                <input className="form-control" placeholder="First Name" defaultValue={first_name}  onChange={e => setFirstName(e.target.value)} required/>
                <label htmlFor="floatingInput">First Name</label>
                </div>
                <div className="form-floating">
                <input className="form-control" placeholder="Last Name"  defaultValue={last_name} onChange={e => setLastName(e.target.value)}  required/>
                <label htmlFor="floatingInput">Last Name</label>
                </div>
                <div className="form-floating">
                <input type="email" className="form-control" placeholder="Email Address" defaultValue={email} onChange={e => setEmail(e.target.value)} required/>
                <label htmlFor="floatingInput">Email Address</label>
                </div>
                <div className="form-floating">
                <select className="form-control" id="floatingRole" placeholder="Role" value={role_id} onChange={e => setRoleId(e.target.value)} required>
                    {roles.map((r: Role) => {
                        return (
                            <option key={r.id} value={r.id}>{r.name}</option>
                        )
                    })}
                </select>
                <label htmlFor="floatingRole">Role</label>
                </div>
                <button className="w-100 btn btn-lg btn-primary" type="submit">Save</button>

            </form>
        </Wrapper>

    );
};

export default UserEdit;

As you can see in this image below, the data isn't show up and get the error message like this

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'params')

error message

I really appreciate if anyone wants to help me solve this problem so I can learn further. Thankyou

CodePudding user response:

In react-router-dom@6 there are no longer "route props", i.e. no location, history (well, now navigate), and no match.

Use the useParams hook to access the route path parameters.

...
import { Navigate, useParams } from "react-router-dom";
...

const UserEdit = (props: any) => {
  const { id } = useParams();

  ...

  useEffect(() => {
    (async () => {
      const response = await axios.get('roles');

      setRoles(response.data);

      const { data } = await axios.get(`users/${id}`);

      setFirstName(data.first_name);
      setLastName(data.last_name);
      setEmail(data.email);
      setRoleId(data.role_id);
    })();
  }, []); // <-- add `id` to dependency array if you need to be responsive

  ...

  return (
    ...
  );
};

CodePudding user response:

It seems like your params not pass correctly .

Maybe you need to get URL parameters by using useParams like document (https://v5.reactrouter.com/web/example/url-params) , or check the Router component path format is correct in your React Router version .

In React Router ^v5.3.0 :

<Route path="users/:id/edit" />
  • Related