skip to Main Content

Sample JSON:

{
  "tutor_id": "1",
  "first_name": "Martin",
  "last_name": "Smith",
  "grade": "Senior",
  "subject": "Integral Calculus",
  "subjects": [{ "subject_id": "2", "subject": "Linear Algebra" }]
}

My goal is to access "subject":"Linear Algebra" in the latter part of the JSON above. tutorDetails.subjects works but tutorDetails.subjects[0] returns an error that ‘0’ is undefined.

Error

My Code:

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;

I tried researching through other resources but, nothing has helped so far.

2

Answers


  1. We’ll need more information to clarify the issue, such as what output you are receiving.

    But from the looks of the posted code, it appears you may need to parse the stringified JSON; "JSON.parse(data)" in order to retrieve the "subjects" array.

    Also, if you’re applying JSON.stringify to the "subjects" array within the object, you’ll also need to JSON.parse the array on top of parsing the whole data object.

    Login or Signup to reply.
  2. tutorDetails has an initial value of [] when the component mounts (initial render), so when you are trying to access tutorDetails.subjects[0] is expectedly throwing an error "Cannot read properties of undefined (reading ‘0’)".

    Instead make sure the data is received before you’re trying to access anything from it by conditionally rendering; and looking at your data sample you’d wanna access subject property from the tutorDetails.subjects[0] Object (since React can’t render Objects):

    <strong>Alternative Subject: </strong> {tutorDetails.subjects !== undefined && tutorDetails.subjects[0].subject} <br/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search