2

I'm learning React now. I have a question.

This is my UserList component. I want to send the id in the selected row with URL, but I cannot get id.

import React,{useState,useEffect} from 'react'
import { Link } from 'react-router-dom'
import UserService from '../services/UserService'

const UserList = () => {

    const [users,setUsers] = useState([])
    
    useEffect(() => {
        UserService.findAll().then((response)=>{
            setUsers(response.data)
            console.log(response.data)
        }).catch(error=>{
            console.log(error)
        })
    }, [])
   const [selectedUserId, setSelectedUserId] = useState();    
   
   let deleteButton = "Delete";
   const handleRowClick = (id) => {
    console.log(id);
    setSelectedUserId(id);
    console.log(id);
  }
 

  return (
    <div className='container'>
        <h2 className='text-center'>Users</h2>
        
        <table className='table table-bordered table-stripped'>
            <thead>        
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th>Password</th>   
            </thead>
            <tbody>
                {
                    users.map(
                        user => 
                             
                        <tr key={user.id} onClick={() => handleRowClick(user.id)} style={{backgroundColor: selectedUserId === user.id ? "lightblue" : ""}}>  
                            <td>{user.firstName}</td>
                            <td>{user.lastName}</td>
                            <td>{user.email}</td>
                            <td>{user.password}</td>
                        </tr>
                    )
                }
            </tbody>
        </table>
        <Link to="/users/save" className="btn btn-primary mx-2">Create</Link>
        <Link className="btn btn-primary mx-2" to={'/update/${selectedUserId}'} >Update</Link>
        <Link to="/users/save" className="btn btn-primary mx-2">{deleteButton}</Link>
    </div>
  )
}
export default UserList;

I checked the selected row Id It's true. And this is my Component I want to send id to.

import React, {useEffect, useState } from 'react'
import UserService from '../services/UserService';
import {Link,useNavigate,useParams} from 'react-router-dom';

const UserCreate = () => {

  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [password,setPassword] = useState('');
  const navigate = useNavigate();
  
  const {id} = useParams();

  
  const createUser = (e)=>{
    e.preventDefault();
    const user = {firstName,lastName,email,password}

    UserService.createUser(user).then((response)=>{
        console.log(response.data)
        navigate.push("/users/save");
    }).catch(error => {
        console.log(error);
    })
  }
  useEffect(()=>{
    UserService.findUserById(id).then((response)=>{
        setFirstName(response.data.firstName)
        setLastName(response.data.lastName)
        setEmail(response.data.email)
        setPassword(response.data.password)
    }).catch(error => {
        console.log(error);
    })
  },[])



  return (
    <div>
        <br/><br/>
        <div className="container">
            <div className="row">
                <div className = "card col-md-6 offset-md-3 offset-md-3">
                    <h2 className="text-center">Update User</h2>                    <div className="card-body">
                        <form>
                            <div className='form-group mb-2'>
                                <label className='form-label'> First Name</label>
                                <input
                                    type='text'
                                    placeholder='Enter First Name'
                                    name='firstName'
                                    className='form-control'
                                    value={firstName}
                                    onChange={(e)=>setFirstName(e.target.value)}
                                >

                                </input>
                            </div>
                            <div className='form-group mb-2'>
                                <label className='form-label'> Last Name</label>
                                <input
                                    type='text'
                                    placeholder='Enter Last Name'
                                    name='lastName'
                                    className='form-control'
                                    value={lastName}
                                    onChange={(e)=>setLastName(e.target.value)}
                                >

                                </input>
                            </div>
                            <div className='form-group mb-2'>
                                <label className='form-label'> Email </label>
                                <input
                                    type='email'
                                    placeholder='Enter Email'
                                    name='email'
                                    className='form-control'
                                    value={email}
                                    onChange={(e)=>setEmail(e.target.value)}
                                >

                                </input>
                            </div>
                            <div className='form-group mb-2'>
                                <label className='form-label'> Password </label>
                                <input
                                    type='password'
                                    placeholder='Enter Password'
                                    name='password'
                                    className='form-control'
                                    value={password}
                                    onChange={(e)=>setPassword(e.target.value)}
                                >

                                </input>
                            </div>
                            <button className='btn btn-success' onClick={(e)=> createUser(e)}> Actions </button>
                            <Link to ='/' className='btn btn-danger'> Back </Link>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>
  )
}

export default UserCreate

For now, I want to get id from url. Where am i wrong?

I tried useParams, I expected it to work. But It was not const {id} = useParams();

philipxy
  • 14,867
  • 6
  • 39
  • 83
  • How does your routes look like? – DreamBold Dec 19 '22 at 20:50
  • ```}> }> }>``` @DreamBold – Mustafa Furkan Bilen Dec 19 '22 at 20:52
  • `const { userId } = useParams();` please try this – DreamBold Dec 19 '22 at 20:54
  • If the `param` is named `userId` in `Route` and the rest of this component is using `id`, perhaps try `const {userId: id} = useParams()`. – John Li Dec 19 '22 at 21:08
  • @DreamBold Here is link, [link] (https://codesandbox.io/s/musing-meninsky-7o29ti?file=/src/components/UserList.js) – Mustafa Furkan Bilen Dec 19 '22 at 21:09
  • The answer of @JohnLi is correct. You could also change the route to be `/update/:id` instead. – adsy Dec 19 '22 at 21:10
  • The route param is `userId`, so to correctly access it in a component it will be `const { userId } = useParams()`, ***OR*** change the route to be `} />`. Also just FYI, the codesandbox you shared is incomplete and is missing dependencies and doesn't run. – Drew Reese Dec 19 '22 at 21:12
  • Answers belong in answer posts, not question posts. So I rolled back your edit putting an answer into the post. Since this is a duplicate, answer posts are blocked. If you want to make it a unique question & post your specific answer you can edit enough to be voted back open as a non-duplicate. PS Debug questions require a [mre]. [ask] Please clarify via edits, not comments. Put all & only what you need to ask your question in the post, not at a link. Please don't insert "EDIT"s/"UPDATE"s, just make your post the best presentation as of edit time. Please delete & flag obsolete comments. [Help] – philipxy Dec 21 '22 at 22:35

0 Answers0