Skip to content
Advertisement

Proper way to perform an API call inside div?

So I am currently trying to display data in a table. This data is from 2 separate tables in the database with foreign keys. I get my list using this call:

 useEffect(()=>{
axios.get("http://localhost:3001/stores").then((response)=>{
    setlistofStores(response.data) //State which contains the response from the API request
});
  }, []);

So I can get the list of Stores and can display them in the table with no issue using this code:

 <TableBody>
      {listofStores.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row) => (
        <TableRow key={row.tenantName}>
          <TableCell>
              <Grid container>
                  <Grid item lg={2}>
                      <Avatar alt={row.unit} src='.' className={classes.avatar}/>
                  </Grid>
                  <Grid item lg={10}>
                      <Typography className={classes.name}>{row.unit}</Typography>
                  </Grid>
              </Grid>
            </TableCell>
          <TableCell>{row.contactName}</TableCell>
          <TableCell>
              <Typography 
                className={classes.status}
                style={{
                    flex: 'center',
                    backgroundColor: 
                    ((row.industry === 'Apparel' && 'purple') ||
                    (row.industry === 'F&B' && 'grey') ||
                    (row.industry === 'Admin' && 'red') ||
                    (row.industry === 'Tech' && 'blue'))
                }}
              >{row.industry}</Typography>
            </TableCell>
          <TableCell>{row.primaryEmail}</TableCell>
            <TableCell>{row.primaryPhone}</TableCell>
            
            <TableCell className={classes.stores}>1</TableCell>
            <TableCell ><button className={classes.viewButton} onClick={()=>{navigate(`/store/${row.id}`)}}>View</button></TableCell>
        </TableRow>

Now I want to run this API inside each row to use the Tenant to display its data:

useEffect(() => {
 axios.get(`http://localhost:3001/store/byId/${id}`).then((response) => {
   setTenant(response.data);
 });
 }, []);

What is the correct way to do this?

Advertisement

Answer

useEffect with empty dependencies is the good one for your situation. You can create a new component for details and by clicking, navigate the user to that component (page). And there you can call the API for details. (or it can be a pop-up. It really depends on your UI design)

const TenantDetails = ({ tenantId, ...props }) => {
  const [tenantData, setTenantData] = useState(null);
  useEffect(() => {
    axios.get(`http://localhost:3001/store/byId/${tenantId}`).then((response) => {
      setTenantData(response.data);
    });
  }, []);

  return (
    // your UI implementation
    <>
      tenantData ? <div> ... </div> : <div>loading</div>
    </>
  )
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement