Home > Net >  Uncaught TypeError: Cannot read properties of undefined but I can see it in the console
Uncaught TypeError: Cannot read properties of undefined but I can see it in the console

Time:11-03

function RequestDetail({match}) {
  const [request, setRequests] = useState({});
  const [data, setData]= useState([]);

  useEffect(() => {
    fetchRequest();
}, []);
const fetchRequest = () => {
  axios
    .get(
      `${baseUrl}/${match.params.id}`
    )
    .then((res) => {
      setRequests(res.data);
      console.log(res.data);
    })
    .catch((err) => console.log(err));
};
                   <Card key={request.id}>
                            <Card.Header>{request.user.email}</Card.Header>
                            <Card.Body>
                            <Card.Title>{request.address}</Card.Title>
                            <Card.Text>
                               {request.description}<br/>
                               {request.kind}
                            </Card.Text>
                            </Card.Body>
                    </Card>

`

in the console I have this enter image description here

any suggestions?

I just want to map the user included in the json, I have tried .map() but it throughs .map() is not a function

CodePudding user response:

Although you initialize your reuest as an empty object in your state, until you fetch the data, your request.user is undefined, so it cannot read the email property.

Some workarounds can be

  1. <Card.Header>{request.user?.email}</Card.Header>

  2. const [request, setRequests] = useState({ user: {} });

CodePudding user response:

It shows the error since the object is initially empty and you are trying to access request.user.email when request = {}.

You can try optional chaining - replace request.user.email with request?.user?.email

Another option is to initialize request with undefined so that you can use conditional rendering.

const [request, setRequest] = useState();
// do this when rendering
{request && 
  <Card key={request.id}>
    <Card.Header>{request.user.email}</Card.Header>
    <Card.Body>
      <Card.Title>{request.address}</Card.Title>
      <Card.Text>
        {request.description}<br/>
        {request.kind}
      </Card.Text>
    </Card.Body>
  </Card>
}

CodePudding user response:

You should wrap Card like this:

{
  request && (
   <Card key={request.id}>
        <Card.Header>{request.user.email}</Card.Header>
        <Card.Body>
          <Card.Title>{request.address}</Card.Title>
          <Card.Text>
            {request.description}
            <br />
            {request.kind}
          </Card.Text>
        </Card.Body>
      </Card>
  )
}
  • Related