TanStackT
TanStack17mo ago
13 replies
moderate-tomato

Best practices for state management and fetching data

I have been using react-query for a few months now but still feel very green. So I have a Quote component with a bunch of form fields that the user can fill in. I am using that same Quote component for both creating a new Quote and editing an existing Quote because that's the point of React, reuse components. So I am trying to figure out how to handle the react-query state in this case.
So here one of my useQuery functions for the Quote component.
    const {
        data: selectedPackaging,
        status: selectedPackagingStatus,
        error: selectedPackagingError
    }: {
        data: {
            packagingGroup: SelectBoxOption | null;
            palletizingGroup: SelectBoxOption | null;
            packagingItems: any[];
            palletizingItems: any[];
        } | undefined;
        status: string;
        error: string | null;
    } = useQuery({
        queryKey: ['quotePackaging', {quoteID: editingQuoteID}],
        queryFn: getQuotePackaging,
        enabled: !!editingQuoteID,
        initialData: initialSelectedPackaging,

So as I understand it, selectedPackaging will be populated with initialSelectedPackaging if this function is not enabled. And then I just update that state as the user fills in the packaging fields with this code: queryClient.setQueryData( ['quotePackaging', {quoteID: editingQuoteID}],...
Am I understanding that all correctly?
Was this page helpful?