Home > database >  After changing a UseState Hook React component is not re-rendering
After changing a UseState Hook React component is not re-rendering

Time:01-22

I read many topics around these problem but none of them helped to find an answer.

I am using a useEffect to fetch an array of objects "nftRewards". And it's working fine cause I can see them on the console. But the part of the render that depends on this hook is not re-render once it was updated. And I don't understand why.

  const [campaignRewardsJson, setCampaignRewardsJson] = useState<nftReward[]>([]);

  type nftReward = {
    title: string;
    description: string;
    imageURL: string;
    price: number;
    quantity: number;
  };


  useEffect(() => {
    if (rewards) {
      const fetchData = async () => {
        var data = await getRewardObject();

        setCampaignRewardsJson(data);
      };
      // call the function
      fetchData().catch(console.error);
    }
  }, [rewards]);

And At the end of my render , I have this but It's never render by react:

{campaignRewardsJson.map((reward, index) => (
            <Card direction={{ base: 'column', sm: 'row' }} overflow="hidden" variant="outline">
              <Image objectFit="cover" maxW={{ base: '100%', sm: '200px' }} src={reward.imageURL} alt="Caffe Latte" />

              <Stack>
                <CardBody>
                  <Heading size="md">{reward.title}</Heading>
                  <Text py="2">{reward.description}</Text>
                </CardBody>

                <CardFooter>
                  <Button variant="solid" colorScheme="blue">
                    Mint NFT
                  </Button>
                </CardFooter>
              </Stack>
            </Card>
          ))}

CodePudding user response:

If rewards is state in this component and type of that is object or array. When you pass array or object to dependency, every render snapshot will compare with previous version. You may try keyword useEffect dependency array and object comparison. for more information.

CodePudding user response:

Try this:

useEffect(() => {
  if (rewards) {
    const fetchData = async () => await getRewardObject();

    // call the function
    fetchData()
      .then(data => setCampaignRewardsJson(data))
      .catch(console.error);
    }
 }, [rewards]);

CodePudding user response:

your useEffect hook has rewards as its dependencies. and it will only run if rewards is true. you need to check that condition.

CodePudding user response:

useEffect(() => {
    if (rewards) {
        await getRewardObject()
            .then(res=>setCampaignRewardsJson(res))
            .catch(console.error)
    }
  }, [rewards]);

Try to write your effect that way. Plus check your rewards value change or not.

This useEffect will run when your component first time render and when even rewards value change.

  • Related