1

I have a REACT NATIVE app and in a component I call with AXIOS an API to get rows from a DATABASE.

I have loadData function that execute the call to the DB and set some info in the STATE to monitor the execution and to save the results. I call this loadData in useEffect but when I change screen I receive Can't perform a React state update on an unmounted component

This is my component:

    const HomeScreen = props => {
    //I take the id from the state
    const Id = useSelector(state => state.auth.Id);



    const [data, setData] = useState();
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState();

    //Manage the duration of the http request
    const [executionDuration, setExecutionDuration] = useState(0);
    const [deleteExecutionCounting, setDeleteExecutionCounting] = useState(0);
    const executionDurationRef = useRef(executionDuration);
    executionDurationRef.current = executionDuration;
    const deleteExecutionCountingRef = useRef(deleteExecutionCounting);
    deleteExecutionCountingRef.current = deleteExecutionCounting;

    //call the api
    //the call to the api has made manually
    const loadData = useCallback(() => {

            setDeleteExecutionCounting(setInterval((() => {
                setExecutionDuration(executionDurationRef.current + 1);
            }), 2000));
            setError(false);
            setLoading(true);
            getRowsFromDb(Id).then(function (response) {
                if (response.status === 204) {
                    setData({ rows: [], count: 0 });
                }
                else {
                    setData(response.data);
                }
            })
            .catch(function (error) {
                setError(true)
            })
            .then(function () {
                // always executed
                clearInterval(deleteExecutionCountingRef.current);
                setExecutionDuration(0);
                setDeleteExecutionCounting(0);
                setLoading(false);
            });



    }, [Id]);

    //this is used to refresh the data every time the screen is visible
    useEffect(() => {
        const unsubscribe = props.navigation.addListener('focus', () => {
            // The screen is focused
            loadData();
        });

        // Return the function to unsubscribe from the event so it gets removed on unmount
        return unsubscribe;
    }, [Id, props.navigation, loadData]);

    useEffect(() => {
        loadData();


    }, [Id, props.navigation, loadData]);

    //check Loading state
    if (loading)
        return (
            <View style={styles.screenMessage}>
                <ActivityIndicator size='large' />
                {executionDurationRef.current > 3 &&
                    (
                        <Text>We're taking too long</Text>
                    )}
                {executionDurationRef.current > 6 &&
                    (<View>
                        <Text>there is something wrong</Text>
                    </View>
                    )}

            </View>
        )

    //check error state
    if (error) {
        console.log(errorOrders);
        return (
            <View style={styles.screenMessage}>
                <Error onPress={() => { loadData(); }}>Try again</Error>
            </View>
        )

    }

    //This is made for the first rendering to avoid to reach the code down when the value should be initialized
    if ((!loading && data === undefined)) {
        return null;
    }


    return (
       //normal rendering of a component
    );
};

const styles = StyleSheet.create({
    screenMessage: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: Colors.bodyBackgroundColor
    },
    bodyContainer: {
        flex: 1,
        justifyContent: "center",
        backgroundColor: Colors.bodyBackgroundColor
    },

});

export default HomeScreen;

How can I solve this?

4
  • Hi ! Could you post your whole component please? I'd need to see the states you defined and your rendering part. Feb 18, 2021 at 16:35
  • Hi @PaulBarrié I modified my answer with the code. Thank you! Feb 18, 2021 at 16:47
  • I think the issue comes from the fact that React tries to render your component before your state has fully been updated. Instead you can add a variable that checks whether your component is mounted are not and render when it's true. Your issue seems duplicated with this one: stackoverflow.com/questions/53949393/… Feb 19, 2021 at 9:44
  • @PaulBarrié I think it's different, with this solution I didn't solve my problem. Feb 22, 2021 at 15:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.