2

Context: I am retrieving a JSON response from a GET request with Axios that uses Async/Await. It is stored in a state variable called tutorDetails within the useMemo hook. I am accessing the stored state variable in React JSX within the return code block, but it's not populated with the intended JSON response prior to displaying the content.

Question: Is there a way I can ensure the return JSX code block is only processed after the state variable has been populated? If not, please suggest any other workarounds.

import React, {useState, useMemo} from "react";
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Slide from '@mui/material/Slide';
import axios from 'axios';

 function TutorCard({tutor_id, first_name, last_name, grade, subject}) {
    return (
        <div className="md:flex bg-white shadow text-gray-800 my-4 py-4 px-10 rounded-md items-center justify-between hover:bg-gray-300"  >
            {/* <img
                style={{ maxWidth: "60px"}}
                className="rounded-full shadow-md border border-gray-300"
                src={image}
                alt="employee"
            /> */}
            <p className="font text-md" style={{ color: 'black', textAlign: "center"}}>{tutor_id}</p>
            <p className="font text-md" style={{ color: 'black', textAlign: "center"}}>{first_name}</p>
            <p className="font text-md" style={{ color: 'black', textAlign: "center" }}>{last_name}</p>
            <p style={{ color: 'black', textAlign: "center" }}>{grade}</p>
            <p style={{ color: 'black', textAlign: "center" }}>{subject}</p>
            <AlertDialogSlide tutorID = {tutor_id} firstName = {first_name} lastName = {last_name} grade = {grade} subject = {subject} />
        </div>
    )
}




const Transition = React.forwardRef(function Transition(props, ref) {
  return <Slide direction="up" ref={ref} {...props} />;
});

function AlertDialogSlide(props) {
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const [tutorDetails, setTutorDetails] = useState([ ])

components (componentDidMount, componentWillMount)
    useMemo( () => {
    const retrieveData = async () => {
        const resp = await axios.get('API call' + props.tutorID);
        console.log("Tutor Info Response: " + JSON.stringify(resp.data));
        console.log("AltSubjects: " + JSON.stringify(resp.data.subjects[0]));
        setTutorDetails(resp.data);

    }

    retrieveData();
}, []);

    

  return (
    <div>
      <Button variant="outlined" onClick={handleClickOpen}>
        {'>'}
      </Button>
      <Dialog
        open={open}
        TransitionComponent={Transition}
        keepMounted
        onClose={handleClose}
        aria-describedby="alert-dialog-slide-description"
        fullWidth = {true}
      >
        <DialogTitle>{props.firstName + " " + props.lastName}</DialogTitle>
        <DialogContent>
          <DialogContentText >
            <strong>Level: </strong> {props.grade} <br/>
            <strong>Subject: </strong> {props.subject} <br/>
            {/* <div> {(tutorDetails.subjects).map(sub => <div>  <strong>Alternative Subject: </strong> {JSON.stringify(sub)} <br/> </div>)} </div> */}
            <strong>Alternative Subject: </strong> {tutorDetails.subjects[0]} <br/>
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Close</Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
export default TutorCard;
0

1 Answer 1

2

You need useEffect to fetch data across the network, not useMemo. Also, depending on what you are doing with tutorDetails in your JSX, and because the callback of a useEffect runs after the JSX is rendered, a loader may make sense, to avoid errors:

const [tutorDetails, setTutorDetails] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
  const retrieveData = async () => {
    const resp = await axios.get("API_URL" + props.tutorID);
    setLoading(false);
    setTutorDetails(resp.data);
  };

  retrieveData();
}, [props.tutorID]);

if (loading) {
  return "Loading...";
}

return <div>Actual Content</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.