I have a dynamic form as a functional component which is generated via a class based component. I want to make reset button which clears the input field values and sets the state to null array.
The values of the form field are stored in state as an array of Items[{}] (initially empty, as users fill up the form fields, items are added in the array)
I want to make a reset button, clearing all the input values and initializing the Items array to null. However, the problem I’m facing is that since, it is a dynamic form and a functional component it doesn’t have a predefined state for each individual form field making it difficult to set value to null. Can someone please help, I’m stuck on this from a long time
As @camperextraordinaire mentioned, it would be helpful if you can clean up the syntax errors. It will make it easier for anyone here to help; we can copy and paste your code into our editors and work from there. If possible and if you have time, maybe reproduce a minimal version of your app in something like codesandbox.io.
Anyway, from my minimal understanding, your Items state resides in your App component. If you pass a reset function as props to the Form component, you can just use the function in a button onClick handler.
I tried replicating your code in codesandbox below:
In the Form component, I used the useState hook to make give the component state-like features.
In your handleReset, you reset the state for itemvalues but not Items. Is that intentional? Do you want to reset the itemvalues only without removing the items?
Yes, it is intentional. Im using Items to generate my input fields. So I want 4 input fields(one for each item). itemvalues on the other hand, is an array which basically stores the input field values.
My onChangeText function is quite complex because I wanted to get the items groupwise.
So, the state for Itemvalues should looks like this:
Yea because, Items array is populated using another function (which I’ve not shown here because it makes an API call). So, I thought it would be easier to create another array which stores the values.
and for resetting the values, im just updating the state, but it is not clearing the input fields, just updating the state
is it because Im using useEffect hook ?
Do I need to use getDerivedState function ?
What I tried was drilling into itemvalues to get the data and create the inputs with that (e.g map through itemvalues instead of Items in your Form component).
That way when you reset your itemvalues, the input fielda will also reset while preserving the state of your Items.
The issue here is my skills are not good enough to implement my own suggestion. Here’s a partial implementation.
Another method is to reset Items instead. Resetting items will reset the input fields too. If your data comes from an API, you can just refetch the data if you want the initial Items data back.
Sorry I can’t be more helpful. At first glance, I thought the problem is simple but I was wrong about that.