https://codesandbox.io/s/friendly-bohr-mjyhc
This is the code snippet of my form, I have created a field and I want to change its value onChange. I don't see the value changing on the screen and when I console log the event.target.value I only see the current letter being replaced from the previous letter (if I type AB, the console log values show A and then it replaces to B)
Formik library itself provides various method to handle the complexity.
In your code rather than adding a custom handle Change you can directly use handleChange method.
Simply replace -
onChange={customChange}
with
onChange={handleChange}
to make this work.
FYI - I also printed values so that you can see the formik bag of values.
Here is the working code -
Code Sandbox
EDIT 1 -
If you want to update the value from a custom handler then you can use setFieldValue for setting the field value.
Working Code - CodeSandBox 1
Related
I'm trying to validate that the form's values actually change before doing a submission, I'm using the form to perform a search also I'm using react-hook-form.
For example these are my fields: { name: 'sample1, mail: 'sample#test.com' }
I want to prevent a sumbmission if the user removes the 1 from the name and then adds it again because the results will be the same
My unique solution at the moment is to store the last values in a state (useState) and inside the submit handler compare each value to determine if something has changed
You can use useWatch or watch to get form values and disable submit button if your values equal the initial values.
My issue was that I was resetting the form after each submission using the defualt values so now I reset the values by providing the last sumbission values so any change to any field will make dirty = true
I am implementing a form in react using react hook form, The form has two select fields country and states.
Second field changes the option based on the selection in first field.
Please see the below sandbox for more details
Creating/submitting the record works perfectly fine.
The problem is: In edit, when I pre populate the values in the form using setValue(), it does not set the second dropdown(state select in the sandbox below) values on the UI but it shows that it has set the value to the field(see in the console for field state).
[CodeSandBox] https://codesandbox.io/s/angry-murdock-h0lbsp?file=/src/App.js
Steps to reproduce:
Open this sandbox in the browser.
Click on the SET ALL VALUES button.
See the blank value in states select
Also, Whats the best way to populate a form like this, i.e. in defaultsValues or useEffect?
What am I missing here, so putting it for the experts here.
Thanks for your time.
The problem you are having is about setValue. This function does not trigger a re-render in most cases. You can use reset instead.
https://react-hook-form.com/api/useform/reset
Also, if you'd like to fill the form without any user interaction, use reset in useEffect with proper dependencies.
Lastly, If you'd like to have just them having initial values instead of being undefined, set defaultValues. It is also recommended in official documents:
Important: You should provide a proper default value and avoid undefined.
undefined is reserved for fallback from inline
defaultValue/defaultChecked to hook level defaultValues. undefined value is conflicting with controlled component as default state
https://react-hook-form.com/api/useform
I am using NextJS, and trying to build a form to update a supplier.
I have the following input:
<input type="text"
ref={nameDisplayedRef}
className='p-2 rounded'
name='nameDisplayed'
defaultValue={supplier.nameDisplayed}
value={supplier.nameDisplayed}
/>
When the input is like this, I cannot type in to it. I have read that I need an onChange function - but I dont need an onChange function. I dont care when its changed, I care when the form is submitted.
The data provided to this input field comes from an API call made by useSWR. When I update the database, the field only updates if I have the value={} in the input field. But with it I cannot change the input text.
I appreciate that i need an onChange function but what am I supposed to put in it? It wont let me leave it empty so I am not sure what to do.
edit:
Adding nameDisplayedRef.current.value = supplier.nameDisplayed solves the problem but typescript shows an error for it in PhpStorm. But the code works at least :\
The problem is controlled vs uncontrolled inputs.
An uncontrolled input is when an input handles value and change on its own.
A controlled input is when you control the input externally. What you want to do is use some kind of state to manage the value of the component (which handles the initial value) and the onChange handler will set the state that is placed in the value.
Here's an example with useState:
const [stateValue, setStateValue] = useState(initialVal)
<input
type="text"
value={stateValue}
onChange={(e)=>setState(e.target.value)}
/>
I have an ArticleFields component that loads an article object (through location.state) which has either empty parameters(when i try to make a new article) or preexisting values when i want to edit an article.My inputs though, won't change when i pass a preexisting value,even if it's an empty string.On the other hand ,the onChange function still works for textarea.Any ideas to why is this happening,i know i can just change the inputs to textareas,but ofcourse i want to understand why this is happening first
Here is a sandbox for reference
https://codesandbox.io/s/green-sound-sopdvp?file=/src/App.js
Use defaultValue instead of value:
value={article.title}
I'm getting my inputs dynamically from an API call based on a change in select input, but when I try to add to the initial values of Formik, it always gives me an error ...
Warning: A component is changing an uncontrolled input of type text to be controlled.
And it doesn't help if I set enableReinitialize={true} to Formik.
However, if I generated the inputs from a local JSON or object, the error goes away.
What am I doing wrong here ...
https://codesandbox.io/s/test-dynamic-inputs-with-formik-xr9qg
The form submits fine though.
Better use enableReinitialize={true}. This is official Formik API.
You can check this issue
If anyone is facing the same issue, I just found the solution ...
You have to set value={field.value || ''} in the input inside the TextInput component or whatever type you're using in order to fix this issue.
I had a complex, dynamic form and also came across this issue. There are a few things that I'd recommend for anyone debugging this issue in the future:
Set value for your Field component--like Ruby does above.
Ensure that your Formik component has a uniquely identifying key.
Track and debug your initialValues and ensure that all fields are accounted for. You shouldn't have to set the field value like Ruby does--so long as your initialValues object accounts for all of the fields. However, my form dynamically changed Field components--and Ruby's solution is the only one that worked.
If your form is not dynamic--I think it might be best to check your initialValues object first before implementing Ruby's solution. Formik should be taking care of those values for you--which is why it's such an awesome tool.
i've checked with enableReinitialize={true}. But its not working as much as expected. so wrote a useEffect like
useEffect(() => {
formik.setFieldValue('query_string', active?.query);
}, [active])
it's worked !