lewiswildman's avatar

How to track form data?

I'm using intertia with wayfinder to build my forms. But I've ran into a situation where I need to track any changes to the form data. However, I can't see any way of doing that?

With the form context, I can do something like form.getData(), but that only returns a snapshot of the data and not the actual state. But on the form context itself, I see no way of getting the state or tracking any of it.

Is there anything that I've missed that may allow me to track the form data and it's state?

0 likes
3 replies
Shivamyadav's avatar

For the vue you can do this

import { watch } from 'vue'

watch(
  () => form.data(),
  (newData, oldData) => {
    console.log('Form changed:', newData)
  },
  { deep: true }
)

lewiswildman's avatar

I probably should've specified I'm using inertia with react. Is there any kind of equivalent to watch in react that you know of?

JussiMannisto's avatar

Can you show which form helper you're using and how you're handing form changes in code? Form helpers usually have built-in methods for listening to changes.

You can monitor form values with React's useForm hook, but you have to be aware of how it tracks its dependencies. It doesn't do deep comparisons, which means you can't simply watch the entire form.getData() output.

useEffect is probably ok for simple forms. This code works if form.getData() returns an object with primitive values:

const {username, password, remember} = form.getData(); 

useEffect(() => {
	// Do something.
}, [username, password, remember]);

But if your form.getData() returns something different, it won't work.

Please or to participate in this conversation.