So i have UserList.jsx component which displays the all user data in a table. enter image description here When i click on edit button it goes to http://localhost:3000/user/id. I have created a form in there to update the user details. The problem is the form is not displaying the specific user data from id. How do i do that? And how to update as well? My UserList.jsx goes like this
import "./userList.css";
import { DataGrid } from '@mui/x-data-grid';
import {DeleteOutline, Block} from '@mui/icons-material';
// import { userRows, trainerRows } from "../../../dummyData";
import { Link } from 'react-router-dom';
import { useState, useEffect } from "react";
export default function UserList() {
const [data, setData] = useState([]);
const [selectedRole, setSelectedRole] = useState('');
const [filteredData, setFilteredData] = useState([]);
// const [sessionID, setSessionID] = useState('');
useEffect(() => {
// Login as admin to get session ID
fetch('http://localhost:3001/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: '[email protected]',
password: 'password123',
}),
})
.then(response => response.json())
.then(data => {
// Store the session ID in localStorage
localStorage.setItem('sessionID', data.session);
// Filter the data based on user_type
// Fetch initial user data
// const url = selectedRole === 'All_User'
// ? 'http://localhost:3001/register_detail/recieve'
// : 'http://localhost:3001/register_detail/recieve';
// Function to get the stored session ID
const sessionId = localStorage.getItem('sessionID');
console.log(sessionId);
fetch('http://localhost:3001/profile/allusers', {
method: 'GET',
headers: {
'session': `${sessionId}`,
},
})
.then(response => response.json())
.then(data => {
// Ensure data is an array of objects
if (Array.isArray(data)) {
setData(data);
setFilteredData(data);
} else {
console.error('Received data is not an array:', data);
}
})
.catch(error => console.error('Error fetching users:', error));
})
.catch(error => console.error('Error logging in:', error));
}, []);
const handleDelete = (id) => {
setData(data.filter(item=>item.id!==id))
}
const handleRoleChange = (event) => {
console.log(event.target.value);
setSelectedRole(event.target.value);
filterData(event.target.value);
};
const filterData = (role) => {
let filtered = [];
if (role === 'All_User') {
filtered = data;
} else {
// data.filter(item => item.user_type === 'trainer'
filtered = data.filter(item => item.user_type.toLowerCase() === role.toLowerCase());
console.log(filtered); //gives data according to filterd event
}
setFilteredData(filtered);
};
const columns = [
{ field: 'user_id', headerName: 'User_ID', width: 70 },
{ field: 'first_name', headerName: 'First Name', width: 150,
// renderCell: (params) => {
// return (
// <div className="userListUser">
// <img className="userListImage" src={params.row.profile_image} alt="Profile" srcset="" />
// {params.row.username}
// </div>
// )
// }
},
{ field: 'last_name', headerName: 'Last Name', width: 150 },
// {
// field: 'email',
// headerName: 'Email',
// width: 200,
// },
// {
// field: 'user_type',
// headerName: 'User Type',
// width: 150,
// },
{ field: 'contact', headerName: 'Contact', width: 150 },
{ field: 'address', headerName: 'Address', width: 150 },
{
field:'action',
headerName:'Action',
width:150,
renderCell: (params) => {
return (
<div className="userListAction">
<Link to = {"/user/" + params.row.user_id}>
<button className="userListEdit">Edit</button>
</Link>
<DeleteOutline className="userListDelete" onClick={() => handleDelete(params.row.id)}/>
<Block className="userListBlock"/>
</div>
)
}
},
];
return (
<div className="userList">
<div className="userDropdown">
<select className= "userDropdownicon" value={selectedRole} onChange={handleRoleChange}>
<option value="All_User">All User</option>
<option value="Trainer">Trainer</option>
<option value="Customer">Customer</option>
</select>
</div>
<DataGrid
rows={filteredData} // Use filteredData instead of data
columns={columns}
getRowId={(row) => row.user_id}
initialState={{
pagination: {
paginationModel: { page: 0, pageSize: 8 },
},
}}
pageSizeOptions={[5, 10]}
checkboxSelection
disableRowSelectionOnClick
/>
</div>
)
}
and my User.jsx goes like this
import "./user.css";
// import axios from 'axios';
import { Link, useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import {CalendarToday, LocationSearching, MailLockOutlined, PermIdentity, PhoneAndroid, Publish} from '@mui/icons-material';
export default function User() {
const {userId} = useParams();
console.log(userId);
useEffect(() => {
fetch('http://localhost:3001/profile/allusers/' +userId)
.then(res => res.json()) // Convert the response to JSON
.then(data=> console.log(data)) //Log the data
.catch(err=>console.log(err));
}, [userId]);
return (
<div className="user">
<div className="userTitleContainer">
<h1 className="userTitle">Edit User</h1>
<Link to="/newUser">
<button className="userAddButton">Create</button>
</Link>
</div>
<div className="userContainer">
<div className="userShow">
<div className="userShowTop">
<img src={process.env.PUBLIC_URL + "/images/admin.jpeg"} alt="" className="userShowImg" />
<div className="userShowTopTitle">
<span className="userShowUsername">Robert Kiyosaki</span>
<span className="userShowUserTitle">Investor</span>
</div>
</div>
<div className="userShowBottom">
<span className="userShowTitle">Account Details</span>
<div className="userShowInfo">
<PermIdentity className="userShowIcon"/>
<span className="userShowInfoTitle">robert99</span>
</div>
<div className="userShowInfo">
<CalendarToday className="userShowIcon"/>
<span className="userShowInfoTitle">02.01.1998</span>
</div>
<span className="userShowTitle">Contact Details</span>
<div className="userShowInfo">
<PhoneAndroid className="userShowIcon"/>
<span className="userShowInfoTitle">0406687956</span>
</div>
<div className="userShowInfo">
<MailLockOutlined className="userShowIcon"/>
<span className="userShowInfoTitle">[email protected]</span>
</div>
<div className="userShowInfo">
<LocationSearching className="userShowIcon"/>
<span className="userShowInfoTitle">Keswick, Adelaide</span>
</div>
</div>
</div>
<div className="userUpdate">
<span className="userUpdateTitle">Edit</span>
<form action="" className="userUpdateForm">
<div className="userUpdateLeft">
<div className="userUpdateItem">
<label>First Name</label>
<input type="text" placeholder="robert99" className="userUpdateInput" />
</div>
<div className="userUpdateItem">
<label>Last Name</label>
<input type="text" placeholder="Robert Kiyosaki" className="userUpdateInput" />
</div>
<div className="userUpdateItem">
<label>Email</label>
<input type="text" placeholder="[email protected]" className="userUpdateInput" />
</div>
<div className="userUpdateItem">
<label>Phone</label>
<input type="text" placeholder="0406687956" className="userUpdateInput" />
</div>
<div className="userUpdateItem">
<label>Address</label>
<input type="text" placeholder="Keswick, Adelaide" className="userUpdateInput" />
</div>
</div>
<div className="userUpdateRight">
<div className="userUpdateUpload">
<img src={process.env.PUBLIC_URL + "/images/admin.jpeg"} alt="userimg" className="userUpdateImg" />
{/* htmlFor Associates this label with an input element using the 'htmlFor' attribute */}
<label htmlFor="file"><Publish className="userUpdateIcon"/></label>
<input type="file" name="" id="file" style={{display:"none"}} />
</div>
<button className="userUpdateButton">Update</button>
</div>
</form>
</div>
</div>
</div>
)
}
The logic i was trying to use is to append the userId at the endpoint of an API /profile/allusers. But it didn’t gave me any data