Repository navigation
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} />
) |
|
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 |
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: |
|
Is there a way to do this without react-hook-form or Formik. Say my component is this: |
Uh oh!
There was an error while loading. Please reload this page.
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!
All reactions