I have this tsx file called AdminUsers. It’s designed to show all the users for an administrator of an application, so they can perform operations on them. The tsx is as follows:
import React, { useState, useEffect } from "react";
import api from "../utils/api";
import { useNavigate } from "react-router-dom";
const API_URL = "http://localhost:8000/api";
const REFRESH_URL = `${API_URL}/token/refresh/`;
interface User {
id: number;
name: string;
role: "customer" | "vendor" | "admin";
}
const AdminUsers: React.FC = () => {
const [users, setUsers] = useState<User[]>([]);
const [searchQuery, setSearchQuery] = useState("");
const [currentPage, setCurrentPage] = useState(0);
const usersPerPage = 10;
useEffect(() => {
const accessToken = localStorage.getItem("accessToken");
api.get("http://localhost:8000/api/users/", {
headers: { Authorization: `Bearer ${accessToken}` },
})
.then((response) => {
console.log("API Response:", response.data); // Debugging step
setUsers(response.data);
console.log("State Updated:", users);
})
.catch((error) => console.error("Error fetching users:", error));
}, []);
const filteredUsers = users.filter((user) =>
user.name?.toLowerCase().includes(searchQuery.toLowerCase())
);
const pageCount = Math.ceil(filteredUsers.length / usersPerPage);
const handlePageClick = ({ selected }: { selected: number }) => {
setCurrentPage(selected);
};
const displayedUsers = filteredUsers.slice(
currentPage * usersPerPage,
(currentPage + 1) * usersPerPage
);
return (
<div>
<h1>User Management</h1>
<input
type="text"
placeholder="Search users..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<table>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
{displayedUsers.map((user) => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.role}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default AdminUsers;
in the useEffect()) function there are two console.log calls, one to show the response. Data from a api call, and the other to show the change of the variable users that is set at the top fo the class.
my problem is that while response.data shows the correct json outputs:
{
"id": 1,
"email": "[email protected]",
"role": "admin",
"is_active": true,
"is_staff": true,
"is_superuser": true
}
the second console.log does not show any change in state to users. Furthermore, the filteredUsers call afterwards fails with a null error on users. What am I missing? is `const [users, setUsers] not global enough? how do I rectify this?
Thanks