Reset form to empty values - reactjs

new to redux-form... I was looking at an example from redux-form docs where one can initialize form values from initialValues (forked example here: https://codesandbox.io/s/6v3n9lwnpr).
Is it possible to have functionality where one can use 'Undo Changes' to reset form to InitialValues, but also have another button to reset to empty form?

If you go to the redux-form documentation, you will find what you need under the action creator section. With that, let's answer your questions.
one can use 'Undo Changes' to reset form to InitialValues
In its documentation, Redux-Form lists out a couple of actions that you can use. You can either use an action creator or used an action that is already bound to the dispatch. For your requirement, you'll need to use the library's reset function
a) using action creator
import { reset } from 'redux-form';
...// then inside a function you can dispatch the reset action.
resetMyForm() {
const action = reset('myFormName');
dispatch(action);
}
b) using an action already bound to the dispatch
I wont type this since there is an example in the library on GitHub here
And as for
button to reset to empty form
similar to the initial answer but you would have to use the clearFields function instead.
Hope this helps.

Related

React Hook Form change default values after API call

How do I update the default values once the API has been called?
This is what I want to achieve:
I have a card where I can see a comment.
There is a button that toggles a textField that allows me to add/edit/delete a comment
I can also discard changes I was making before saving an edition, to do so I will show the original defaultValues
Now let's say I've already left a comment Comment test 1, so when the card is rendered it will show the comment by using the injected data of the defaultValues. I edit the comment to Comment test 2, and click save, now the comment shown comes from the state value, not from the default values. Now I want to edit to Comment Test 3, but I change my mind and discard the changes. Now the card will show default values Comment Test 1, while it should show Comment Test 2.
So I guess there's a way to update the defaultValues once the API has been called, I have tried on success to use
resetField('comment', { defaultValue: { ...comment } });, but the default comment is not updated.
What would be a better approach to the problem?
What you can do is, storing the values you save in a variable (e.g. overwrittenForm) Than use the formContext.reset(overwrittenForm) from the useForm hook and pass it the variable to reset to the latest state.

react hook form - watch vs onchange , which one would be the right approach

I am using watch,setValue and getValues to update one dropdown selected value based on another dropdown selected value.
It can be also done using dropdown list's onChange so, onChange, setValue and getValues so no need to use of watch.
Can you please guide, watch is performance cost then using onChange or it will be fine with watch how its implemented below (without onChange).
const dropdownList_1_watch_value = watch(dropdownList_1);
useEffect(()=>{
if (dropdownList_1_watch_value !== 'specificValue') && getValues(dropdownListControlName) !== defaultValue)
{
setValue(another_dropdownListControlName, defaultValue);
}},[dropdownList_1_watch_value]);
return (
<>
// list of dropdown list components and other controls
</>
);
Regarding performance there shouldn't be much of a difference between those to.
I will cite from a blog post:
React Watcher should be used sparingly, in cases where you can't
really solve the problem any other way. In most cases, where you need
to do something when some prop changes, you don't really need it. Why?
Because in most cases you can usually trigger the event together with
the action with caused the prop to be changed, e.g. when triggering a
filtering change on a listing.
Full post: http://sborrazas.com/blog/react-watcher

Where do I want to code filters to get a more granular piece of redux state?

I have a somewhat comprehensive object that exists within my redux-store and I want to condense it down to just an array of specific keys. Do I want to code this filter logic in mapStateToProps ?
Typically, I have something that takes form like so:
const mapStateToProps = state => {
return {
budgetCategories: state.getIn(['budget', 'budgetCategories']).toJS(),
budgetFormEditable: state.getIn(['budget', 'budgetFormEditable']).toJS(),
reduxForm: state.getIn(['form']).toJS()
}
}
Wondering if I want to strip out single item using a filter and map, if it would be reasonable to put this is the same function.
Sounds like you need selectors.
Redux documentation suggests to put them alongside the reducer because if the state form changes, selectors will need to be changed as well.
https://redux.js.org/docs/faq/CodeStructure.html#structure-file-structure

redux state in componentWillRecieveProps issue with forward and back button

I have problem showing an alert dialog using redux. I want to show a success message after user has edited says a form. I set a flag through action > reducer > store.
Then I do
componentWillReceiveProps(nextProps) {
if(nextProps.data.updated_form) {
alert('form has been updated!');
}
}
There's problem in this approach. User updated the form, then he click somewhere to go to other route, then he click back to my form, that alert will trigger too.
The problem with your existing solution is that updated_form variable of the store doesn't change over time. So getting back to the page retriggers the alert. One simple solution would be to create another action creator to reset those changes on componentWillUnmount()`.
sample store reducer could like this
case 'RESET_CHANGES':
return {...state,updated_form:null}
And the react component will have similar code like this
componentWillUnmount() {
this.props.resetChanges() // assuming you have created action creator
}

redux-forms initialization not working after upgrade to 7.x

I have upgraded my recct-redux application to user redux-form 7.x (latest at this time). After update, initial values aren't getting populated in the form. (It used to work with redux-forms 2.x)
Is it a bug or am i doing something silly ?
Below is my code link
https://github.com/santhoshml/Bookbild-UI/blob/master/src/components/user_profile.js
[Update] : I found the problem (but I still don't have an answer) ,
I made 3 calls to the backend server and each one returned at it own time and each kept overwriting the other. If I keep refreshing, the values keep doing disco :)
Now I have wrapped all the 3 calls in Promise.all and I can see all the fields populated, BUT when I edit and submit, onClickHandler doesn't have any updated values.
To debug this, I printed the props in the render and it does not have the values returned from db. But surprisingly the values are populated in the textfields. This is amazingly confusing. Please help. Link below
https://github.com/santhoshml/Bookbild-UI/blob/master/src/components/user_profile.js
Thank you in advance,
Santhosh mL
Did you check this documentation out. According to that you will need to connect() to the Redux state yourself and map from the data reducer to the initialValues prop. So it should be something like this.
// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
InitializeFromStateForm = reduxForm({
form: 'initializeFromState' // a unique identifier for this form
})(InitializeFromStateForm)
// You have to connect() to any reducers that you wish to connect to yourself
InitializeFromStateForm = connect(
state => ({
initialValues: state.account.data // pull initial values from account reducer
}),
{ load: loadAccount } // bind account loading action creator
)(InitializeFromStateForm)
export default InitializeFromStateForm
What you need to do is provide the action to load the data. Then map over the data and set it into the initialValues property.

Resources