I have a registration form in which the user can select multiple roles through a checkbox. These roles are saved in a database and this already does it correctly, then I have a modal which is used for the user to edit their roles. In this a checkbox is shown again with the roles that they can select.
What I want to achieve is that when the modal is displayed, the roles that the user already has assigned appear marked in the checkbox. I achieve but this only works when I reload the page. What can I do so that as soon as the modal is displayed, the roles that the user has are already marked without having to reload the page?
This is my code:
import React, { useEffect, useState } from "react";
import { supabase } from "../supabase/client";
//import FormEditRoles from "./FormEditRole";
import RegisterFormUser from "./RegisterFormUser";
import SignOut from "./SignOut";
import TableUser from "./TableUser";
const CrudUser = () => {
const [db, setDb] = useState({});
const [dataRol, setDataRol] = useState({});
const [nameRol, setNameRol] = useState([]);
const [dataUserRol, setDataUserRol] = useState({});
const [dataToEdit, setDataToEdit] = useState(null);
const [user, setUser] = useState([]);
const getAuthenticatedUserData = () => {
try {
supabase.auth.getUser().then(async (value) => {
setUser(value.data.user);
});
} catch (error) {
console.error(error.message);
}
};
const getUserData = () => {
try {
supabase.auth.getUser().then(async (value) => {
const user = value.data.user;
const { data } = await supabase
.from("users")
.select()
.eq("email", user.email);
setDb(data);
});
} catch (error) {
console.error(error.message);
}
};
const getRoles = async () => {
try {
const { data } = await supabase.from("roles").select("*");
setDataRol(data);
} catch (error) {
console.error(error);
}
};
const getDataTabRolesUser = async () => {
try {
const { data } = await supabase.from("users_roles").select("*");
setDataUserRol(data);
} catch (error) {
console.error(error.message);
}
};
useEffect(() => {
const getUserRole = async () => {
try {
const { data } = await supabase
.from("users")
.select("roles(nombre)")
.eq("email", user.email);
const auxNameRol = [];
if (data.length > 0) {
data[0].roles.map((el) => auxNameRol.push(el.nombre));
}
setNameRol(auxNameRol);
} catch (error) {
console.log(error.message);
}
};
getUserRole();
}, [dataUserRol, user]);
useEffect(() => {
getUserData();
getRoles();
getDataTabRolesUser();
}, []);
useEffect(() => {
getAuthenticatedUserData();
}, []);
const createDataUser = async (data) => {
try {
data.user_id = Date.now();
await supabase.from("users").insert({
user_id: data.user_id,
email: user.email,
nombres: data.nombres,
apellidos: data.apellidos,
fecha_nacimiento: data.fecha_nacimiento,
is_active: true,
});
console.log("Register added successfully");
setDb([...db, data]);
} catch (error) {
console.error(error.message);
}
};
const createRolesUser = (data) => {
data.roles.map(async (el) => {
await supabase
.from("users_roles")
.insert({ user_id: data.user_id, rol_id: el });
setDataUserRol([...dataUserRol, data]);
});
};
const deleteDataUser = async (id) => {
let isDelete = window.confirm("Are you sure to delete your data?");
if (isDelete) {
try {
await supabase.from("users_roles").delete().eq("user_id", id);
await supabase.from("users").delete().eq("user_id", id);
let newData = db.filter((el) => el.user_id !== id);
setDb(newData);
console.log("The record was deleted");
} catch (error) {
console.error(error.message);
}
} else {
return;
}
};
const updateDataUser = async (data, updateFields) => {
const { error } = await supabase
.from("users")
.update(updateFields)
.eq("user_id", data.user_id);
let newData = db.map((el) => (el.user_id === data.user_id ? data : el));
setDb(newData);
if (error) throw error;
};
return (
<div>
<div className="grid-1-2">
<RegisterFormUser
data={dataRol}
userData={db}
createDataUser={createDataUser}
createRolesUser={createRolesUser}
dataToEdit={dataToEdit}
updateDataUser={updateDataUser}
setDataToEdit={setDataToEdit}
/>
<br />
<br />
<TableUser
dataUser={db}
nameRol={nameRol}
setDataToEdit={setDataToEdit}
deleteDataUser={deleteDataUser}
dataRol={dataRol}
setDataUserRol={setDataUserRol}
dataUserRol={dataUserRol}
/>
<SignOut />
</div>
</div>
);
};
export default CrudUser;
import TableRowUser from "./TableRowUser";
const TableUser = ({ dataUser, nameRol, setDataToEdit, deleteDataUser, dataRol, setDataUserRol, dataUserRol, loadRoles}) => {
return (
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Last names</th>
<th>Birthdate</th>
<th>Rol</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{dataUser.length > 0 ? (
dataUser.map((el) => (
<TableRowUser
key={el.user_id}
el={el}
nameRol={nameRol}
setDataToEdit={setDataToEdit}
deleteDataUser={deleteDataUser}
dataRol={dataRol}
setDataUserRol={setDataUserRol}
dataUserRol={dataUserRol}
dataUser={dataUser}
/>
))
) : (
<tr>
<td colSpan="5">You have not entered additional data</td>
</tr>
)}
</tbody>
</table>
</div>
);
};
export default TableUser;
import { useModal } from "../hooks/useModal";
import FormEditRoles from "./FormEditRole";
import Modal from "./Modal";
const TableRowUser = ({
el,
nameRol,
setDataToEdit,
deleteDataUser,
dataRol,
setDataUserRol,
dataUserRol,
dataUser,
}) => {
let { user_id, nombres, apellidos, fecha_nacimiento } = el;
const [isOpenModal, openModal, closeModal] = useModal(false);
return (
<tr>
<td>{nombres}</td>
<td>{apellidos}</td>
<td>{fecha_nacimiento}</td>
{nameRol.length > 0 ? (
<td>{nameRol.join(", ")}</td>
) : (
<td>empty data</td>
)}
<td>
<button onClick={() => setDataToEdit(el)}>Edit</button>
<button onClick={openModal}>Edit roles</button>
<button onClick={() => deleteDataUser(user_id)}>Delete</button>
<div>
<Modal isOpen={isOpenModal} closeModal={closeModal}>
<FormEditRoles
dataUser={dataUser}
dataRol={dataRol}
setDataUserRol={setDataUserRol}
dataUserRol={dataUserRol}
/>
</Modal>
</div>
</td>
</tr>
);
};
export default TableRowUser;
import React, { useEffect, useState } from "react";
import { supabase } from "../supabase/client";
const initialForm = {
roles: [],
};
const FormEditRoles = ({ dataUser, dataRol, setDataUserRol, dataUserRol }) => {
const [form, setForm] = useState(initialForm);
const [selectedRoles, setSelectedRoles] = useState([]);
const [message, setMessage] = useState();
const [response, setResponse] = useState(null);
useEffect(() => {
const loadSelectedRoles = async () => {
const { data: userRoles } = await supabase
.from("users_roles")
.select("rol_id")
.eq("user_id", dataUser[0].user_id);
const selectedRoles = userRoles.map((r) => r.rol_id);
setSelectedRoles(selectedRoles);
};
if (dataUser && dataUser.length > 0) {
loadSelectedRoles();
}
}, [dataUser]);
const handleCheckboxChange = (e) => {
const roleId = parseInt(e.target.value, 10);
if (e.target.checked) {
setSelectedRoles([...selectedRoles, roleId]);
setForm({ ...form, roles: [...selectedRoles, roleId] });
} else {
setSelectedRoles(selectedRoles.filter((id) => id !== roleId));
setForm({
...form,
roles: selectedRoles.filter((id) => id !== roleId),
});
}
};
const updateRolesUser = async () => {
const { data: userRoles } = await supabase
.from("users_roles")
.select("rol_id")
.eq("user_id", dataUser[0].user_id);
//Gets the IDs of the roles to be removed
const rolesToDelete = userRoles.filter(
(r) => !form.roles.includes(r.rol_id)
);
//Removes roles that are no longer selected by the user
for (const role of rolesToDelete) {
await supabase
.from("users_roles")
.delete()
.eq("user_id", dataUser[0].user_id)
.eq("rol_id", role.rol_id);
}
//When removing any role we update the data
let newData = dataUserRol.filter(
(el) => el.user_id !== dataUser[0].user_id
);
setDataUserRol(newData);
//Gets the IDs of the roles to be add
const rolesToAdd = form.roles.filter(
(r) => !userRoles.some((ur) => ur.rol_id === r)
);
for (const roleId of rolesToAdd) {
await supabase
.from("users_roles")
.insert({ user_id: dataUser[0].user_id, rol_id: roleId });
}
setDataUserRol([...dataUserRol, dataUser]);
setMessage("Roles actualizados exitosamente");
setResponse(true);
setTimeout(() => {
setResponse(false);
}, 2000);
};
return (
<>
<h3>Edit roles</h3>
{dataRol.length > 0 ? (
dataRol.map((el, index) => (
<div key={index} className="inline-role">
<input
type="checkbox"
id={`role-${el.roles_id}`}
value={el.roles_id}
name={el.nombre}
checked={selectedRoles.includes(el.roles_id)}
onChange={handleCheckboxChange}
/>
<label htmlFor={`role-${el.roles_id}`}>{el.nombre}</label>
</div>
))
) : (
<p>Loading...</p>
)}
<button onClick={updateRolesUser}>Guardar</button>
{response && <p>{message}</p>}
</>
);
};
export default FormEditRoles;
Comments
Post a Comment