T
TanStack2y ago
stormy-gold

Accessing all mutations, filtered by variables + preventing duplicate mutations in MutationCache

I have an array that is used to render input fields. Each input triggers mutate whenever onBlur is triggered. For example: 1. User enters a value in input 'a', e.g. 'hello' (the variable), and blur is triggered 2. mutate gets called with key ['commonkey', 'a'] and returns some data 3. Input value changes to 'bye' (the variable) in child 'a', blur is triggered 4. mutate (with key ['commonkey', 'a']) is called again I want to accomplish a few things: 1. Prevent duplicate mutate calls for keys + variables that already exist in the MutationCache. If a mutation for a key with some variable is successful, that data is considered final. 2. This means that if the user enters 'hello', mutate is called and the Mutation is added to the cache, then 'bye', then 'hello' again, it should notice that 'hello' already exists in the cache; it should simply return the existing cached data or do nothing 3. I want to access the data of all mutations in the parent and filter them based on the current values of each input. What is the best way to check the cache for a specific key + variable to determine if mutate should be called?
const items = ['a', 'b', 'c']

function Parent() {
const currInputValues = useCurrValues()
// ^? { a: 'hello', b: '', c: '' } example

// filter state based on curr values
const data = useMutationState({
filters: { mutationKey: ['commonkey'] }
})

return (
<div>{items.map((item) => <Child key={item} />)}</div>
)
}

function Child({ item }) {
const { field } = useController({ name, control })

const { mutate } = useMutation({
mutationKey: ['commonkey', item],
mutationFn: ({ value }) => getSomeData(item, value)
})

return (
<Input
value={field.value}
onChange={field.onChange}
// If mutation with key ['commonkey', item]
// and variables { value } exist on MutationCache
// don't call mutate
onBlur={(value) => mutate({ value })}
/>
)
}
const items = ['a', 'b', 'c']

function Parent() {
const currInputValues = useCurrValues()
// ^? { a: 'hello', b: '', c: '' } example

// filter state based on curr values
const data = useMutationState({
filters: { mutationKey: ['commonkey'] }
})

return (
<div>{items.map((item) => <Child key={item} />)}</div>
)
}

function Child({ item }) {
const { field } = useController({ name, control })

const { mutate } = useMutation({
mutationKey: ['commonkey', item],
mutationFn: ({ value }) => getSomeData(item, value)
})

return (
<Input
value={field.value}
onChange={field.onChange}
// If mutation with key ['commonkey', item]
// and variables { value } exist on MutationCache
// don't call mutate
onBlur={(value) => mutate({ value })}
/>
)
}
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?