Skip to main content

How to handle a checkbox in react if I want certain checkboxes to already appear checked?

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;
Via Active questions tagged javascript - Stack Overflow https://ift.tt/8jUhGH5

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data