Setting a state variable using another state variable?
12:12 01 Mar 2023

I have a state variable minSearchDate which retrieves a date, populated by the getMinSearchDate function with a call to the setter.

This works fine, with minSearchDate being rendered in the view..

However, my issue is using the state variable minSearchDate to populate another state variable: searchDateFrom. In this case, undefined is always being returned probably because minSearchDate in this instance is either undefined or not accessible.

Why would that be the case?

const [minSearchDate, setMinSearchDate] = useState("");

useEffect(() => {
    getMinSearchDate();
}, []);

const getMinSearchDate = async () => {
    setIsLoading(true);
    if (doGetMinSearchDate) {
        await doGetMinSearchDate().then(async ({ minDate }) => {
            setIsLoading(false);
            setMinSearchDate(minDate);
        });
    }
};

const [searchDateFrom, setSearchDateFrom] = useState(
    dateFromQueryString
        ? new Date(JSON.parse(dateFromQueryString))
        : minSearchDate
        ? new Date(JSON.parse(minSearchDate))
        : undefined
);
reactjs