0

I've been trying to find out how to set when a function should be triggered within the useEffect() hook and therefore rendered.

I need to render on a table the transactions made from the user logged in in the app by passing the user id, which is the foreign key in the transaction's table, when the user logs in I only get username, password and access token from the user. So the only way I found to get the information from the logged in User {username, id, name...} was by using the username provided by the user when he/she signed in.

It is working but the component has to make about three petitions before data renders on the table and two of those petitions are failed at first as it says that the ID that I'm passing is "undefined". As shown in the following screenshot:

Console errors

Code:

import React, { useContext } from 'react'
import { useEffect } from 'react';
import Table from 'react-bootstrap/Table';
import { CdrsContext } from '../contexts/CDRDownloadingContext';
import { UserContext } from '../contexts/UserContext';
import UseAuth from '../hooks/UseAuth';
import styles from './stylePages/CDRDownloading.module.css'

const CDRTable = () => {
    const { getUserDetails, record } = useContext(UserContext)
    const { cdrListFiltered, getCdrsListMadeByUser } = useContext(CdrsContext);
    const { auth } = UseAuth();

    /*************************************
    * GETTING THE USER ID TO GET THE LIST OF REPORT REQUESTS SENT BY THE SPECIFIC USER
    //*************************************/
    // Auth.username is providin an object type user from the backend, which among the properties
    // it contains the user id. 
    const extractedUsername = auth.username;
    console.log(extractedUsername);
    // Once the user details have been loaded with the getUserDetails(extractedUsername); function which expects a username to get data.
    // I get the especific user and with the record 
    const extractedUserById = record.serie;
    console.log(extractedUserById)
    //**************************************/

    /**
     * Function to mount the list of report requests made by the logged in user
     */
    useEffect(() => {
        getUserDetails(extractedUsername);
        getCdrsListMadeByUser(extractedUserById)
    }, [extractedUserById]);

    const typeReport = {
        0: 'Cliente',
        1: 'Proveedor'
    }

    const callFilter = {
        0: 'Contestadas',
        1: 'No contestadas',
        2: 'Todas'
    }

    return (
        <>
            <div>
                <br />
            </div>
            <Table className={styles.table}>
                <thead className={styles.tableHead}>
                    <tr>
                        <th>ID</th>
                        <th>FECHA CONSULTA</th>
                        {/* <th>ID USUARIO</th> */}
                        <th>EMAIL</th>
                        <th>FECHA INICIAL</th>
                        <th>FECHA FINAL</th>
                        <th>TIPO REPORTE</th>
                        <th>NOMBRE CLIENTE/PROVEEDOR</th>
                        <th>RGIDs</th>
                        <th>ESTADO</th>
                        <th>PROCESO INICIADO</th>
                        <th>PROCESO FINALIZADO</th>
                        <th>FILTRO LLAMADA</th>
                    </tr>
                </thead>
                <tbody>
                    {cdrListFiltered?.map((report, reportIndex) => (
                        <tr key={reportIndex} >
                            <td>{reportIndex + 1}</td>      
                            <td>{report.requestDate}</td>
                            {/* <td>{report.requestUserId}</td> */}
                            <td>{report.requestEmail}</td>
                            <td>{report.startDate}</td>
                            <td>{report.endDate}</td>
                            <td>{typeReport[report.reportType]}</td>
                            <td>{report.contactId}</td>
                            <td>{report.rgids}</td>
                            <td>{report.status}</td>
                            <td>{report.processStart}</td>
                            <td>{report.processFinish}</td>
                            <td>{callFilter[report.callQuery]}</td>
                        </tr>
                        )
                    )}
                </tbody>
            </Table>
        </>
    )
}

export default CDRTable

Does anyone know how I can do so that this does not happen, how can I make it render once I have the variable that continues the user's ID ready? to pass it as a function parameter, and not have it called on the first render?

Rosh343
  • 33
  • 6
  • You can check if `auth.username` is truthy inside the `useEffect`. Is that what you're looking for? – ivanatias Oct 13 '22 at 20:45
  • I can confirm `auth.username` is truly inside de `useEffect`, it is in the function `getUserDetails(extractedUsername)`; so it returns the user object with the props, but then what I need is to handle when the `useEffect `getCdrsListMadeByUser(extractedUserById)` function is triggered, as it expects as a parameter the user `Id` to render the list of transactions and by the time the `useEffect` is render the function returns an error stating that the id is **undefine** because it doesn't have the user `id` yet, only until I get it on with `record.serie`. – Rosh343 Oct 13 '22 at 21:21
  • Ok, then you can check if `extractedUserById` is populated before `getCdrsListMadeByUser` executes (not executing it if the user id is `undefined`). – ivanatias Oct 13 '22 at 21:43
  • Should I put the condition within the `useEffect` or outside in another function that will be called within the useEffect? How can I write this particular condition stating that a function was excecuting before another one, could you please give an example? – Rosh343 Oct 13 '22 at 22:29
  • It's up to you, the end result should be the same: the function won't execute if the user id is falsy. Basically: `if (extractedUserById) { function(extractedUserById) }`. – ivanatias Oct 13 '22 at 22:47
  • Thanks a lot! I appreciate your help, it helped me clear up my mind. – Rosh343 Oct 14 '22 at 02:36

0 Answers0