Unable to reset multiple checkbox values after submitting in formik

366 Views Asked by At

So I am using Formik and MUI. I am unable to reset checkbox values after submitting.

I have tried useRef, states, setFieldsValue to manipulate this. But no luck. (I might be doing something in the wrong way probably)

Let me know if there is any mistake or workaround that I am missing. Or if you have any suggestions for this.

Below is the code that can be refferred.

Main Form

const LeadForm = () => {
    const [loc, setLoc] = useState({});

    const handleSubmitForm =(values, formik) =>{
        let googleLocation = [];
        Object.keys(loc).forEach((e) => {
            loc[e]===true && googleLocation.push(e);
        })

        const postData={
            user_google_location: googleLocation.join(','),
        }
       
        Axios.post(`...url`, qs.stringify(postData))
        .then(response =>{
          ...some toast
        }).catch(err=>console.log(err))
    }
    let location = [
       {
         id: 1,
         typeValue: Delhi
       },
       {
         id: 2,
         typeValue: Punjab
       }
    ]

    return (
        <div className={Styles.FormDiv}>
            <Formik
                initialValues={{
                    user_google_location:''
                }}
                onSubmit={ (values) => {
                    handleSubmitForm(values);
                }}
            >
            {({
                values,
                errors,
                handleChange,                
                handleSubmit,
                }) => {
                return <Form onSubmit={handleSubmit}>
                    {
                        location.map((e, index) => 
                        <div key={index}>
                            <CheckBoxSelectors
                                id={e.id}
                                values={values}
                                setLoc={setLoc}
                                loc={loc}
                                label={e.typeValue}
                            />
                        </div> 
                        )
                    }
                    <button type="button" className={Styles.SubmitButton} 
                        onClick={() => {
                            handleSubmitForm(values);
                            handleReset();
                        }}
                    >
                        SUBMIT
                    </button>
                </Form>}
            }
            </Formik>
        </div>
    )
};

export default LeadForm;

CheckBoxSelectors Component

import React, {useEffect} from 'react';
import { withStyles } from '@material-ui/core/styles';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';

const BlueCheckbox = withStyles({
    root: {
      '&$checked': {
        color: "#1c75c0",
      },
    },
    checked: {},
  })((props) => <Checkbox color="default" {...props} />);


export default function CheckboxLabels(props) {
  const {label, values, id, loc, setLoc} = props
  const handleChange = (event, value) => {
    let obj = {};
    obj[event.target.name] = event.target.checked;
    setLoc({...loc, ...obj});
  };

  return (
    <div>
      <FormGroup>
         {...normal div...}
         <FormControlLabel
            control={
              <BlueCheckbox
                checked={values[checkBox[0].name]}
                onChange={handleChange}
                name={checkBox[0].name}
                color="primary"
              />
            }
         />
      </FormGroup>
    </div>
  );
}
3

There are 3 best solutions below

1
Quyen Nguyen On

https://formik.org/docs/api/formik#resetform-nextstate-partialformikstatevalues--void I think that it can help your case.

e/g:

<Formik
   initialValues={{
      ...
   }}
   onSubmit={ (values, actions) => {
      handleSubmitForm(values);
      actions.resetForm({
         values: {
           // the type of `values` inferred to be Blog
           title: '',
           image: '',
           body: '',
         },
      });
   }}
>

or

const handleSubmitForm = (values, actions) => {
    your logic...
    actions.resetForm({values: {...}})
}
<Formik
       initialValues={{
          ...
       }}
       onSubmit={ (values, actions) => {
          handleSubmitForm(values, actions);
       }}
    >
0
Hewali Gogoi On

Solved by my own!

CheckBoxSelectors Component


    const BlueCheckbox = withStyles({
        root: {
          '&$checked': {
            color: "#1c75c0",
          },

          //changed mui class on each event

          '&:not($checked) .MuiIconButton-label:after':{
            color: 'white'
          }
        },
        checked: {},
      })((props) => <Checkbox color="default" {...props} />);
    
    
    export default function CheckboxLabels(props) {

      //previous code
    
        <BlueCheckbox
          checked={loc[checkBox[0].name]}  --> changed loc[...] from values[...]
          onChange={handleChange}
          name={checkBox[0].name}
                                    ----> removed color="primary"
        />
    
    
      //previous code
    }

For the time being this is working. Still open to any suggestions if any.

0
AudioBubble On

Remove the onChange from checkbox and add in FormControlLabel. I did in my project like this:

<FormControlLabel
   control={<Checkbox checked={formik.values.percentage} />}
   label="Percentage"
   name="percentage"
   onChange={formik.handleChange}
/>