Adrian
Adrian

Reputation: 347

Can't call setState function in onSubmit of Formik

I'm trying to add an alert every time I submit my form. I tried to pass my state as a prop to my component but that doesn't seem to work.

Here is my class state:

this.state = {
          alert_variant: '',
          alert_heading: '',
          alert_body: '',
          alert_show: false
};

Here is how I render my Alert:

<ReactAlert 
  show={this.state.alert_show}
  variant={this.state.alert_variant} 
  heading={this.state.alert_heading} 
  body={this.state.alert_body} 
/>

Here is a portion of my submit handler in Formik which sends the values to API:

onSubmit={(
          values, 
          {
           setSubmitting, 
           resetForm
          }) =>{
                fetch("url.com", {
                        method: 'POST',
                        mode: 'cors',
                        body: JSON.stringify(values, null, 2)
                    }
                )
.then(res => res.json())
.then(
(result) => {
       console.log(result)
       setSubmitting(false)
       resetForm(values)
       this.setState({
               alert_show: true,
               alert_variant: 'success',
               alert_heading: 'Sample Header',
               alert_body: 'Sample body.'
       });
},
    (error, result) => {
                        this.setState({
                            error
                        });
                        console.log(this.state.error);
                        setSubmitting(false);
                    }
                )

And here is my Alert component:

function ReactAlert(props){
    const [show, setShow] = useState(false);
    if (show) {
        return(
            <Bs.Alert variant={props.variant} onClose={() => setShow(false)} dismissible>
                <Bs.Alert.Heading>{props.heading}</Bs.Alert.Heading>
                <p>
                    {props.body}
                </p>
            </Bs.Alert>
        );
    }
    return null;
}

Now how can I change my state variable within the submit handler of Formik? Is that even possible? I tried to create a separate submit handler function but that didn't work either.

Upvotes: 0

Views: 4018

Answers (2)

Adrian
Adrian

Reputation: 347

I found a solution to my problem. I'm sharing this if there are any beginners out there who will encounter the same problem.

I created a variable to store the this instance of the class just like what @Harish Sonis' said in his answer. And I added a function that I call every time the alert is closed.

My function:

alertClose(){
     this.setState({
        alert_show: false
     });
}

New Alert render, I added the onClose prop:

<ReactAlert 
            display={this.state.alert_show}
            variant={this.state.alert_variant} 
            heading={this.state.alert_heading} 
            body={this.state.alert_body} 
            onClose={this.alertClose}
        />

I called the onClose prop in the component render

function ReactAlert(props){

    if (props.display) {
        return(
            <Bs.Alert variant="success" onClose={() => props.onClose()} dismissible>
                <Bs.Alert.Heading>hehe</Bs.Alert.Heading>
                <p>
                    hehe    
                </p>
            </Bs.Alert>
        );
    }
    return null;
}

Thanks to @Harish Soni for helping me.

Upvotes: 1

Harish Soni
Harish Soni

Reputation: 1896

You don't have the instance of the Current Class inside the fecth as it creates a new object which scopes until the end.

So if you want to call setState inside of another class here is way:

onSubmit={(
        values,
        {
          setSubmitting,
          resetForm
        }) => {

        // GET THE CURRENT CLASS INSTANCE:
        const that = this;

        fetch("url.com", {
          method: 'POST',
          mode: 'cors',
          body: JSON.stringify(values, null, 2)
        }
        )
          .then(res => res.json())
          .then(
            (result) => {
              console.log(result)
              setSubmitting(false)
              resetForm(values)

              //CALL SETSTATE ON THAT
              that.setState({
                alert_show: true,
                alert_variant: 'success',
                alert_heading: 'Sample Header',
                alert_body: 'Sample body.'
              });
            },
            (error, result) => {

              //CALL SETSTATE ON THAT
              that.setState({
                error
              });
              console.log(that.state.error);
              setSubmitting(false);
            }
          )
      }

UPDATE: For the Alert ONE

function ReactAlert(props){
    const [show, setShow] = useState(false);
    if (props.show || props.alert_show) {
        return(
            <Bs.Alert variant={props.variant} onClose={() => setShow(false)} dismissible>
                <Bs.Alert.Heading>{props.heading}</Bs.Alert.Heading>
                <p>
                    {props.body}
                </p>
            </Bs.Alert>
        );
    }
    return null;
}

Upvotes: 1

Related Questions