use SWR with a controlled form #561
Replies: 4 comments 6 replies
-
@ThePaulMcBride if you want to change the data in form directly, I think import useSWR from 'swr'
const {data, mutate} = useSWR(API)
function handleChange() {
mutate(/* any data you want */)
}
return (
<Form data={data} onChange={handleChange} />
) |
Beta Was this translation helpful? Give feedback.
-
I use SWR with Formik elegantly. Like you said, you set the initial data of the form to the object from your backend. In my case, the user object that I can edit from the backend is different from the one I display. const editableUser = useSWR('/api/user?editable=true')
const displayUser = useSWR(/api/'user')
const editUser = useEditUser()
const onSubmit = async (form) => {
const newUser = await editUser(form)
displayUser.mutate(newUser)
closeForm()
}
if (!editableUser.data) return <Loading />
return <Formik onSubmit={onSubmit} initialValues={editableUser.data) /> Since I always want the |
Beta Was this translation helpful? Give feedback.
-
function App() {
const { data } = useQuery() // data returns { firstName: '', lastName: '' }
const { register, handleSubmit } = useForm({
values: data,
resetOptions: {
keepDirtyValues: true, // keep dirty fields unchanged, but update defaultValues
},
})
} What about this example from official documentation: |
Beta Was this translation helpful? Give feedback.
-
Is there a way to do this without react-hook-form or Formik. Say my component is this:
|
Beta Was this translation helpful? Give feedback.
-
Does anyone have a good example of how to use SWR with a controlled form.
Lets say I have a form that show some data I got from the server using SWR. Would I need to take that data, store it as the initial value in a useState hook, then user the setter function to update it or does SWR have something built in to help with this?
Any pointers would be really appreciated!
Beta Was this translation helpful? Give feedback.
All reactions