T
TanStack4w ago
afraid-scarlet

PARTIAL data update

If you do router.invalidate(), then all the data from the loader will be reloaded, which is not very effective if there is a lot of data, but only part of it has been updated. through experimentation, I came to the conclusion that I need to do a hook to work with server functions in order to first receive data from loader, but then update only them. some server functions:
export const counterServerFunctionGet = createServerFn({ method: 'GET' }).handler(()=>{ ... })
export const counterServerFunctionSet = createServerFn({ method: 'POST' }).handler(({ data }) => { ... })
export const counterServerFunctionGet = createServerFn({ method: 'GET' }).handler(()=>{ ... })
export const counterServerFunctionSet = createServerFn({ method: 'POST' }).handler(({ data }) => { ... })
the hook:
export function useMyCustomHook({ fallbackData}: { fallbackData: any }) {

const query = useQuery({
queryKey: ['custom-hook'],
queryFn: counterServerFunctionGet,
initialData: fallbackData,
enabled: !fallbackData, // don't fetch if fallbackData is already populated
})

const mutation = useMutation({
mutationFn: async (data: any) => counterServerFunctionSet({ data }),
onSuccess: () => query.refetch()
})

return { ...query, mutation }
}
export function useMyCustomHook({ fallbackData}: { fallbackData: any }) {

const query = useQuery({
queryKey: ['custom-hook'],
queryFn: counterServerFunctionGet,
initialData: fallbackData,
enabled: !fallbackData, // don't fetch if fallbackData is already populated
})

const mutation = useMutation({
mutationFn: async (data: any) => counterServerFunctionSet({ data }),
onSuccess: () => query.refetch()
})

return { ...query, mutation }
}
and than use it like this
const { data: loaderData } = Route.useLoaderData()
const { data, mutation } = useMyCustomHook({ fallbackData: loaderData })

function handleClick() {
mutation.mutate({ step: 1 })
}

return (
<div>
{JSON.stringify(data)}
<Button onClick={handleClick}>+</Button>
</div>
)
const { data: loaderData } = Route.useLoaderData()
const { data, mutation } = useMyCustomHook({ fallbackData: loaderData })

function handleClick() {
mutation.mutate({ step: 1 })
}

return (
<div>
{JSON.stringify(data)}
<Button onClick={handleClick}>+</Button>
</div>
)
it works. data is not requested unnecessarily, and in case of changes, only the necessary part of the data is changed. but it all looks like overhead… shouldn't such things be solved simply and out of the box, so as not to describe such a structure for each data block?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?