0
votes

I'm learning react native and I'm programing a simple app to register the time of sleep of each day.

When the button that add the new register is pressed I do this

onPress={() => setUpdateAction(true)}

That changes the value of the updateAction:

const [updateAction, setUpdateAction] = useState(false);

When the value of updateAction is changed this will be executed:

useEffect(() => {

    ... code that add's the register to an array

    setviewInfoAction(true);
    setUpdateAction(false);
}, [updateAction]);

And inside I call setviewInfoAction(true); becouse I want to change the value that is showed with the value that was inserted.

const [viewInfoAction, setviewInfoAction] = useState(false);


useEffect(() => {
        console.log("CALLED");
        var seted = false;
        for (var i = 0; i < registSleep.length; i++) {
            if (
                registSleep[i].day === selectedDay &&
                registSleep[i].month === selectedMonth &&
                registSleep[i].year === selectedYear
            ) {
                setSelectedDayHours(registSleep[i].hours);
                seted = true;
            }
        }
        if (!seted) {
            setSelectedDayHours(0);
        }
        setviewInfoAction(false);
    }, [viewInfoAction]);

Doing this I was expecting for the second UseEffect to executed but it's not...

1
Just add the value, changed by first useEffect, into the second useEffect dependencies. In your case, I guess, it should be updateAction - Pavlo Zhukov

1 Answers

0
votes

The way you have your useEffect set up it will only ever re-run if selectedDay changes. If you want to make it run when setInfoViewAction is executed add viewInfoAction into the dependencies.

Even better because all of this is related logic to the same sideEffect. I would simplify your code by removing the second useEffect and adding the code inside it into the first useEffect. This is mainly just because you can keep all related side effect logic together.