Home > Blockchain >  React component not rendering on state update
React component not rendering on state update

Time:11-09

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.

CodePudding user response:

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>
  );
})}

CodePudding user response:

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>
  );
}
  • Related