1

I have a component which is working, however I'm getting the following warning:

Warning: Cannot update a component (`HomeInfoCard`) while rendering a different component (`StackCount`). To locate the bad setState() call inside `StackCount`

Here is the component, which I think the issue is coming from the fact that StackCount component also attempts to use setTrackingCount, but I am too noob to understand how to resolve this issue. How can I fix? Code is below:

HomeInfoCard.js

import { API } from "aws-amplify";
import React, { useState } from "react";
import { View } from "react-native";
import { Card, Headline, Text } from "react-native-paper";
import useAsync from 'react-use/lib/useAsync';
import { useUser } from "../../context/UserContext";
import { listUserStacks } from "../../graphql/queries";

const HomeInfoCard = () => {
    const { user } = useUser();
    const username = user.username;
    let filter = {
        UserID: {eq: username}
    };

    const stacksState = useAsync(async () =>
        API.graphql({
            query: listUserStacks,
            variables: { filter: filter },
            authMode: 'AMAZON_COGNITO_USER_POOLS'
        })
    , []);

    const [trackingCount, setTrackingCount] = useState('');

    const StackCount = ({value}) => {
        const stacksData = value.data.listUserStacks.items
        const stackCount = stacksData.length

        let trackCount = stacksData.filter(function (stack) {
            return stack.StackTrack === true;
        })

        if (trackCount.length > 0) setTrackingCount(trackCount.length)

        return (
            <View style={{paddingHorizontal: 20, paddingBottom: 10}}>
                <Headline>{`${stackCount}`}</Headline>
            </View>
        );
    };

    return (
        <Card>
            <Card.Title title='Protocols' subtitle={`Traking ${trackingCount}`}/>
            {stacksState.loading
                ? <Text>Loading...</Text>
                : stacksState.error
                    ? <Text>Error</Text>
                    : <StackCount value={stacksState.value}/>
            }
        </Card>
    );
};

export default HomeInfoCard;
3
  • 2
    You're calling setTrackingCount in your StackCount main function, but the main function is what's called during a render, and rendering must not change the state.
    – user5734311
    Commented Mar 31, 2022 at 17:26
  • 2
    You need to move the logic that determines trackingCount into a useEffect function that depends on stacksState, then pass the value as prop to your StackCount component.
    – user5734311
    Commented Mar 31, 2022 at 17:29
  • Thanks for the pointer, resolved the warning!
    – patataskr
    Commented Mar 31, 2022 at 18:26

0

Browse other questions tagged or ask your own question.