In the picture below, i wanted to select multiple or single users with checkbox and set their status to Active/Blocked but the code is not working properly.By selecteing multiple users with checkboxes i am able to delete but i have no idea how to push user status together with id inside array to change Active/Blocked status. If something not clear please ask. Can anyone help how to make request for BE and handle from BE to change status to Active/Blocked?
Here is my source code:
const Home = ({status, setStatus}) => {
const token = localStorage.getItem("token");
const [users, setUsers] = useState([]);
const [isCheckAll, setIsCheckAll] = useState(false);
const [isChecked, setisChecked] = useState([]);
const handleDeleteUser = async () => {
const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
method: "DELETE",
body: JSON.stringify(isChecked),
headers: {
"Content-Type": "application/json",
},
});
if(response.status === 200){
const data = await response.json()
setUsers(users.filter(user => !data.find(row => row === user._id)))
}
};
const handlecheckbox = (e) => {
const { value, checked } = e.target;
if (checked) {
setisChecked([...isChecked, value]);
} else {
setisChecked(isChecked.filter((e) => e !== value));
}
}
const handleSelectAll=()=> {
setIsCheckAll(!isCheckAll);
setisChecked(users.map(user => user._id));
if (isCheckAll) {
setisChecked([]);
}
}
}
isChecked is an array of selected user ids with checkbox. I dont know how to make request for BE to update user status.
return (
<tbody>
{users.map((user) => (
<tr key={user._id}>
<td>
<Form.Group>
<Form.Check
type="checkbox"
value={user._id}
checked={isCheckAll ? isCheckAll : user.isChecked}
onChange={(e) => handlecheckbox(e)}
/>
</Form.Group>
</td>
<td>{user._id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{format(parseISO(user.lastLogin), 'EEEE, MMM. do - HH:mm')}</td>
<td>{format(parseISO(user.createdAt), 'EEEE, MMM. do - HH:mm')}</td>
<td>{isChecked.includes(user._id) ? status: "Active"}</td>
</tr>
))}
</tbody>
)
Here is schema of user in BE :
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const userSchema = new Schema(
{
name: { type: String },
email: { type: String, unique: true},
password: { type: String },
status: {type: String, enum:["Active", "Blocked"], default:"Active"},
token: { type: String },
lastLogin: { type: Date, default: Date.now},
},
{ timestamps: true }
);
export default model("User", userSchema);
Aucun commentaire:
Enregistrer un commentaire