Goal:
It's about the Material Autocomplete from material-ui for React in variant freeSolo. I understand that one is asked to handle value and inputValue independently, but because Formik and Yup are used to save the state and apply validation I would prefer to have only one value outside. For splitting this increases complexity in the outer code noticeably.
Attempt:
https://codesandbox.io/s/autocomplete-with-a-single-state-v442c?file=/demo.tsx
Is an example where I set the prop inputValue to value.title || '' and in onInputChange I check if the inputValue matches an existing option and otherwise create a new object, both to mimic onChange.
Issue:
Unfortunately, the list does not become filtered anymore. I had added some logging in my attempt was everything worked as expected and I can't infer what issue the component runs into. I hope anyone has some idea or ideally working code? So again, my overall goal is to have only one value representing the state and that, therefore, needs to be an object.
So I realised this can not be done because the states value and inputValue update at different times. value is only affected by inputValue once the user clears the input completely, setting inputValue to '' and value becoming null. So the asynchronous nature does not allow storing it in a single value in a clean way.
Related
I have a piece of code where Formik is used in the #React app with #Typescript and Yup validation. The problem I am facing is that on setting the values in a Select element it does not change the value at all or perhaps it immediately resets the value to the initial value as given in the Formik initial value object. What should I do about it? (No code is available here. But hopefully)
This issue is resolved.
In my case enableReinitialize is the culprit.
It was just the enableReinitialize property in the initial Values object set to true. You just need to remove this and you are good to go. I tried dozens of patches to cope with the problem and due to this property, each and every property was not working according to the logic. I also used #MUI #DatePicker #MUIDatePicker which was having issues because of this one property.
Hope it helps many others.
#Coding
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 have a Ant Design 4.x.x Form element without multiple Form.Item. I need to implement some logic involving form items' values, for example disabling a field if another one's value equals something, or recalculate select options when a text input changes.
To do so, I create the form using Form.useForm() and use form.getFieldValue() in my functional component body and / or in the returned JSX, like so :
It is working as I expect to, but at startup, getFieldValue usages throw annoying
index.js:1 Warning: Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?
I found that Form functions cannot be used before rendering, and the problem also occured when displaying a form in a Modal like stated in the docs.
So I feel that I'm missing something on how to correctly add custom logic between fields, or doing some calculation involving fields values in component body.
What would be a correct approach to do this ?
Try adding getContainer={false}, to your modal this will work for you.
I have created the following demo to help me describe my question: https://codesandbox.io/s/dazzling-https-6ztj2
I have a form where I submit information and store it in a database. On another page, I retrieve this data, and set the checked property for the checkbox accordingly. This part works, in the demo this is represented by the dataFromAPI variable.
Now, the problem is that when I'd like to update the checkboxes, I get all sorts of errors and I don't know how to solve this. The ultimate goal is that I modify the form (either uncheck a checked box or vice versa) and send it off to the database - essentially this is an UPDATE operation, but again that's not visible in the demo.
Any suggestions?
Also note that I have simplified the demo, in the real app I'm working on I have multiple form elements and multiple values in the state.
I recommend you to work with an array of all the id's or whatever you want it to be your list's keys and "map" on the array like here https://reactjs.org/docs/lists-and-keys.html.
It also helps you to control each checkbox element as an item.
Neither your add or delete will work as it is.
Array.push returns the length of the new array, not the new array.
Array.splice returns a new array of the deleted items. And it mutates the original which you shouldn't do. We'll use filter instead.
Change your state setter to this:
// Since we are using the updater form of setState now, we need to persist the event.
e.persist();
setQuestion(prev => ({
...prev,
[e.target.name]: prev.topics.includes(e.target.value)
// Return false to remove the part of the array we don't want anymore
? prev.topics.filter((value) => value != e.target.value)
// Create a new array instead of mutating state
: [...prev.topics, e.target.value]
}));
As regard your example in the codesandbox you can get the expected result using the following snippet
//the idea here is if it exists then remove it otherwise add it to the array.
const handleChange = e => {
let x = data.topics.includes(e.target.value) ? data.topics.filter(item => item !== e.target.value): [...data.topics, e.target.value]
setQuestion({topics:x})
};
So you can get the idea and implement it in your actual application.
I noticed the problem with your code was that you changed the nature of question stored in state which makes it difficult to get the attribute topics when next react re-renders Also you were directly mutating the state. its best to alway use functional array manipulating methods are free from side effects like map, filter and reduce where possible.
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 !