#isMutating in useSWRMutation change when fetch data but dont change in UI

1 messages · Page 1 of 1 (latest)

frozen knot
#

I'm use useSWRMutation for fetch data (method: POST)
this hook return a isMutating state
when i pass it to disable properties of submit button then press submit, but button dont disable
i have log this state to console, isMutating still change to 'true' when i submit and change to 'false' when data is returned

hasty umbraBOT
#

Hi @frozen knot. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Hmm, I don't know enough to give you a confident answer yet. The knowledge sources provided do not contain information about useSWRMutation or its isMutating state. However, they do provide examples of how to handle loading states and form submission in Next.js using React hooks and state.

For instance, you can use the useState hook to manage a loading state. When a form is submitted, you can set this state to true, and then set it back to false when the request completes. This state can be used to disable the submit button while the form is being submitted. Here's an example from the Next.js documentation (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#displaying-loading-state):

import React, { useState, FormEvent } from 'react'
 
export default function Page() {
 const [isLoading, setIsLoading] = useState<boolean>(false)
 
 async function onSubmit(event: FormEvent<HTMLFormElement>) {
 event.preventDefault()
 setIsLoading(true) // Set loading to true when the request starts
 
 try {
 const formData = new FormData(event.currentTarget)
 const response = await fetch('/api/submit', {
 method: 'POST',
 body: formData,
 })
 
 // Handle response if necessary
 const data = await response.json()
 // ...
 } catch (error) {
 // Handle error if necessary
 console.error(error)
 } finally {
 setIsLoading(false) // Set loading to false when the request completes
 }
 }
 
 return (
 <form onSubmit={onSubmit}>
 <input type="text" name="name" />
 <button type="submit" disabled={isLoading}>
 {isLoading ? 'Loading...' : 'Submit'}
 </button>
 </form>
 )
}
#

For more specific information about useSWRMutation, I would recommend checking the official SWR documentation or relevant resources.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@frozen knot kapa.ai is still learning and improving, please let us know how it did by reacting below