TanStackT
TanStack4y ago
14 replies
endless-jade

Syncing react query data with useState state

Hi all, I have a provider which is fetching a list of "KeyRecord" from the backend.
This provider provides the state of a list of forms, each form allows to edit a single KeyRecord.
When the provider is done fetching the list of KeyRecord from the backend, it needs to initialize the state of the forms.
The problem is, because I do that with a useEffect, there is a small timeframe where isLoading is false, and keyRecordsFormState is an empty array [] and I would like to get rid of that because it causes an unnecessary render of the consumers with an empty list.

Code:
type KeyRecordsProviderProps = {
    children: ReactElement;
};

export const KeyRecordsProvider = (props: KeyRecordsProviderProps) => {
    const { children } = props;
    const { page } = usePagination();
    const {
        data: keyRecords = [],
        isLoading,
        isError,
    } = useQuery(["keyRecords", page], () => getKeyRecords(page));
    // State of the form list of key records (editable list of forms in the UI, one form per key record)
    const [keyRecordsFormState, setKeyRecordsFormState] = useState<KeyRecord[]>(
        []
    );

    useEffect(() => {
        if (!isLoading) {
            // When the key records have been fetched from the backend, assign the value to the form state
            setKeyRecordsFormState(keyRecords);
        }
    }, [isLoading]);

    return (
        <KeyRecordsContext.Provider
            value={{
                isError,
                isLoading,
                keyRecordsFormState,
            }}
        >
            {children}
        </KeyRecordsContext.Provider>
    );
};
Was this page helpful?