2

I am loading some data from my API, it is returned successfully, but React is not rendering the cards afterwards.

export default function Subjects() {
  const userApi = useUserService();
  const auth = useRecoilValue(AuthAtom);
  const [loading, setLoading] = React.useState<boolean>(true);
  const [subjects, setSubjects] = React.useState<Subject[]>();

  React.useEffect(() => {
    userApi.getSubjects(auth?.userId ?? 0).then((value: Subject[]) => {
      setSubjects(value);
      setLoading(false);
    });
  }, []);

  return (
    <Box display="flex" flexDirection="row" alignItems="center">
      {!loading &&
        subjects?.map(function (subject: Subject) {
          <Card key={subject.name}>
            <CardActionArea>
              <CardContent>{subject.name}</CardContent>
            </CardActionArea>
          </Card>;
        })}
    </Box>
  );
}

userApi.getSubjects returns an array of Subjects.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Heldenkrieger01
  • 338
  • 3
  • 16
  • See [this](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) and [this](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value). – T.J. Crowder Nov 08 '21 at 12:49
  • @T.J.Crowder Thank you, I understand my mistake now!! – Heldenkrieger01 Nov 08 '21 at 12:53

2 Answers2

3

You don't return anything inside the .map callback, so your component doesn't render anything. To fix it:

subjects?.map(function (subject: Subject) {
  // add the return statement like below.
  return (
    <Card key={subject.name}>
      <CardActionArea>
        <CardContent>{subject.name}</CardContent>
      </CardActionArea>
    </Card>
  );
})}
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
2

Your function in the body do not return anything. Try this:

return (
    <Box display="flex" flexDirection="row" alignItems="center">
      {!loading &&
        subjects?.map(function (subject: Subject) {
          return (
             <Card key={subject.name}>
               <CardActionArea>
                 <CardContent>{subject.name}</CardContent>
               </CardActionArea>
             </Card>;
          );
        })}
    </Box>
  );
}
noiseymur
  • 761
  • 2
  • 15