T
TanStack14mo ago
generous-apricot

State syncing with local state - is there a better way?

So I was reading this article from TkDodo where he basically says that state syncing is to be avoided if at all possible https://tkdodo.eu/blog/breaking-react-querys-api-on-purpose . So I'm wondering the best way to handle this situation. I have a useQuery that gets a list of quotes that each have a quote ID. The quotes are displayed in a table with a checkbox next to each quote. Now I have a local state for checkedQuoteIDs to keep track of which ones are checked. I want them all to be checked by default to begin with. Here is my useQuery and state:
const [checkedQuoteIDs, setCheckedQuoteIDs] = useState<string[]>([]);

const queryClient = useQueryClient();

const {
data: quoteList,
isLoading: gettingQuotes,
status: quotesStatus
} = useQuery<{
tableData: { mainHeader: string; chemicals: any[] }[],
editableQuoteData: {
quoteNo: string,
altPrice: string,
load: string,
category: string,
chemical: string,
}[]
categories: string[],
chemicals: any[]
} | undefined>({
queryFn: getQuoteTableDataByPriceListID,
queryKey: ['quotesByPriceListID', priceList.id],
enabled: !!priceList?.id,
});
const [checkedQuoteIDs, setCheckedQuoteIDs] = useState<string[]>([]);

const queryClient = useQueryClient();

const {
data: quoteList,
isLoading: gettingQuotes,
status: quotesStatus
} = useQuery<{
tableData: { mainHeader: string; chemicals: any[] }[],
editableQuoteData: {
quoteNo: string,
altPrice: string,
load: string,
category: string,
chemical: string,
}[]
categories: string[],
chemicals: any[]
} | undefined>({
queryFn: getQuoteTableDataByPriceListID,
queryKey: ['quotesByPriceListID', priceList.id],
enabled: !!priceList?.id,
});
Is a better option to add a select into that useQuery and add a checkedQuotes array to the quoteList object? Or should I be using my local state variable to keep track of checked quotes? How do I initially set them all as checked then?
Breaking React Query's API on purpose
Why good API design matters, even if it means breaking existing APIs in the face of resistance.
3 Replies
optimistic-gold
optimistic-gold14mo ago
Maybe uncheckedQuoteIDs? Inverse condition?
foreign-sapphire
foreign-sapphire14mo ago
just store what the user does. If it's "unselecting" items, you store which items are unselecetd and derive the rest
generous-apricot
generous-apricotOP14mo ago
ok, thanks guys, its definitely a mind shift from what I'm used to

Did you find this page helpful?