#Mutation with refetch

70 messages · Page 1 of 1 (latest)

spare swallow
#

Hey, I am having a ListDisplay on my Frontend which fetches an array. After I mutate that array like deleting one object, it should show the new array in this ListDisplay…How can I force a refetch after a mutation?

heavy spruce
spare swallow
#
const mutateTwitch = useMutation({
        mutationFn: (data: SocialType) => insertOrUpdateTwitchChannel(props.currentServer.id, data),
        onSuccess: () => queryClient.invalidateQueries({queryKey: ["twitch-notification"]})
    })```
#
    const {data, isLoading} = useQuery('twitch-notification', () => fetchTwitchChannel(serverId ?? "0"))
#

This still does not refetch somehow

spare swallow
heavy spruce
#

queryKeys need to be arrays, so this is wrong:

- useQuery('twitch-notification'
- +useQuery(['twitch-notification']
#

also, prefer the object syntax:

const {data, isLoading} = useQuery({
  queryKey: ['twitch-notification'],
  queryFn: () => fetchTwitchChannel(serverId ?? "0")
})
spare swallow
#

Ok thx👍🏼

#

I am going to try that tomorrow

spare swallow
#

Still does not refetch somehow

spare swallow
#

This is my full code currently

heavy spruce
#

please boil it down to a minimal reproduction on codesandbox

spare swallow
#

Okay

#

Which api for fetching could I use? Cause mine is not online

heavy spruce
#

Promise.resolve does the job just fine

spare swallow
#

ah ok

spare swallow
spare swallow
#

But why doesnt anything change?

spare swallow
#

Okay I got the problem

#

My Backend is responding with the old data...Probably it is too fast requesting the data...What could I do to fix this? I delete something and my spring backend responds with two elements even I just deleted one

spare swallow
#

I see that the onSuccess is called before it mutated something...My Backend received the refetch and then the delete

#

2023-10-21 18:33:38.213 DEBUG 3553 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Secured GET /api/discord/embed-manager/

#

2023-10-21 18:33:38.615 DEBUG 3553 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

#

According to console.log it first mutates and then refetches.......But I see what my backend firstly receives

heavy spruce
#

Your backend returns too early. It needs to "await" until the mutation actually finished

spare swallow
spare swallow
#

Let me check this

heavy spruce
#

The get request could also be a window focus refetch ... it's really hard to say without seeing a repo but I'm almost 100% sure that RQ works fine in this scenario and the problem is somewhere else

spare swallow
spare swallow
#

I read the docs and it should only run the onSuccess if the delete was completed…Maby it is a problem from my Frontend

#

Aha...it now creates after the refetch...Maby react query does run the onSuccess instantly....Is React query compatible with ky?

#

Because this is how my method for deleting looks like

#
    return api.delete(`${ORIGIN}/embed-manager/`, {
        headers: {
            'X-Server': serverId,
            'X-UUID': uuid
        }
    }).formData
}```
spare swallow
heavy spruce
#

Maby react query does run the onSuccess instantly.
it does not

Is React query compatible with ky?
yes because it doesn't matter what produces the promise

spare swallow
#

Hmm

#

Because it does send a refetch when the delete didn’t respond yet

#

When does it run onSuccess?

#

Even if it receives an error?

#

Cause my backend returns 404 cause I removed the endpoint and it received a 200 for fetching and a 404 for deleting

#

Tbh a 404 for the mutation after the 200 (refetch)..

heavy spruce
#

When does it run onSuccess?

After the mutationFn returns a resolved promise

spare swallow
#

I am going to artificially delay the response in the mutation and then I can see if something is not working correctly

spare swallow
#

Wait…I’ve got React Query in my Project….Not tanstack/react-query

#

Could that be an issue?

#

My react query ist v3

spare swallow
#

@heavy spruce I just saw that React Query 4 and 5 are even other packages on npm.com…..Could this be a problem? I still have 3

heavy spruce
#

no. feel free to update but react-query has always executed onSuccess after the mutationFn. You can easily verify this with something like this:

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))

useMutation({
  mutationFn: async () => {
    console.log('before request')
    // simulate request that takes 1s
    await sleep(1000)
    console.log('after request)
    return "some-data"
  }
  onSuccess: () => {
    console.log('onSuccess')
  }
})

Just replace your mutation with that and you should see the order of things clearly. So your problem is somewhere else and unless you're showing a minimal codesandbox, there's nothing I can do because sorry, it's a waste of my time.

spare swallow
spare swallow
# heavy spruce no. feel free to update but react-query has always executed `onSuccess` _after_ ...

This is my code...I am sorry I somehow dont get it managed to fix all those errors...Some things somehow dont work on this....There you can see everything from the QueryService and How I fetch the data and mutate it. I dont really now how I build it so you can test it but this is basically everything I did...Of course I changed some things to : any instead of all the types and so on but this shouldnt break anything. Tell me if you need something. Thanks again for your time

spare swallow
#

Tk?

spare swallow
#

@heavy spruce do you need more stuff?

heavy spruce
#

I'm not looking into this until you show a small reproduction. the queryService is empty. There's tons of glue code, everything is red. Sorry, I already said that you should replace your actual fetching with a promise.resolve and you'll see that it works. I can't spend my time on this anymore, sorry

spare swallow
#

okay let me try this again....

#

bruh queryservice is indeed empty

spare swallow
#

@heavy spruce https://codesandbox.io/s/dreamy-buck-gysp6s Now it should have saved my code this time....I edited it but it didnt save my changes....With those Promises it works perfectly but as soon as I add my query to this...It wont work again....I commented my ky query additionally into this queryService.ts so you see if I use it the wrong way ( I personally didnt find anything different on how to use it.)...Is there a way it returns a Promis instantly in my case?

dreamy-buck-gysp6s by killingsausage using ky, loader-utils, react, react-dom, react-query, react-scripts

solar junco
#

Use async mutationfn eg:
mutationFn: async (uuid) => deleteEmbed(xx)

Call it with mutateAsync() instead of mutate().

Inside the query function await the ky call.
Eg.

Res = await ky.delete().
Return res.formData

  • some guy
#

Onsuccess is running because your query returns before your server finishes work because you aren't waiting for it properly..... probably idk

spare swallow
#

I just found the error

#

my deleteEmbed looked like this: tsx export async function deleteEmbed(serverId: string, uuid: string) { return api.delete(`${ORIGIN}/embed-manager/`, { headers: { 'X-Server': serverId, 'X-UUID': uuid } }).formData }

#

After I removed formData it worked with the refetch after delete

#

prop. because formdata returns a promise