What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments)

Here is the relevant code snippet:

private async handleSubmit(e: React.FormEvent): Promise<any> {
    e.preventDefault();
    try {
        console.log(`These are the reset params---->${JSON.stringify(Reset.resetParams)}`)
        const resetService = new ResetService();
        const resetResponse: ResetResponse = await resetService.reset(Reset.resetParams);
        console.log(`This is the response from the API ----> ${JSON.stringify(resetResponse}`)

        if (resetResponse.status === 401) {
            console.log("Authentication failed");
        } else if (resetResponse.status === 200) {
            console.log("Password reset successfully");
            const resetSuccess: boolean = true;
            this.setState({ resetSuccess }); // ****How do I set this state? which is in the class's scope?
            Reset.history.push('/login');
        }
    } catch (e) {
        console.log(`Request failed: ${e}`);
        const resetSuccess: boolean = false;
        this.setState({ resetSuccess });
    }
}

This is how it looks like after rendering:

public render() {
    const { resetSuccess, errors } = this.state;
    const context: FormContext = {
        ...this.state,
        setValues: this.setValues,
        validate: this.validate
    };
    return (
        <IonPage id="login-registration-page">
            <IonHeader>
                <IonToolbar color="primary">
                    <IonTitle>Reset Password</IonTitle>
                </IonToolbar>
            </IonHeader>
            <IonContent>
                <FormContext.Provider value={context}>
                    <form onSubmit={this.handleSubmit} className="login-registration-form ion-padding">
                        <div className="container">
                            {this.props.render()}
                            <div className="form-group">
                                <IonButton
                                    type="submit"
                                    disabled={!this.completeValidation}
                                    expand="block"
                                >Submit</IonButton>
                            </div>
                            {resetSuccess === true && (     //*****This is what I am trying to display based on the outcome
                                <div className="alert alert-info" role="alert">
                                    Password reset successfull. You will be redirected shortly to the login page
                                </div>
                            )}
                            {resetSuccess === false &&
                                (
                                    <div className="alert alert-danger" role="alert">
                                        Either the link that you have clicked on or the current password you provided is incorect. Please use the right verification link you received and input the correct password.
                                    </div>
                                )}
                        </div>
                    </form>
                </FormContext.Provider>
            </IonContent>
        </IonPage>
    )
}

Answer №1

To achieve this, one effective method is to create a function that generates and returns the desired handleSubmit function utilizing the appropriate setState handler. This approach allows you to leverage the component's scope for passing the preferred setState method to your handleSubmit function.

private async handleSubmit(): 
  (e: React.FormEvent) => Promise<any> {
        const setState = this.setState; // Define local reference to setState

        return (e: React.FormEvent) => {
        e.preventDefault();
        try {
            console.log(`These are the reset parameters ----> ${JSON.stringify(Reset.resetParams)}`)
            const resetService = new ResetService();
            const resetResponse: ResetResponse = await resetService.reset(Reset.resetParams);
            console.log(`API response ----> ${JSON.stringify(resetResponse)}`)

            if (resetResponse.status === 401) {
                console.log("Authentication failed");

            }
            else if (resetResponse.status === 200) {
                console.log("Password reset successful");
                const resetSuccess: boolean = true;
                setState({ resetSuccess }) // Using the local reference
                Reset.history.push('/login');
            }
        } catch (e) {
            console.log(`Request failed: ${e}`);
            const resetSuccess: boolean = false;
            setState({ resetSuccess }) // Using the local reference
        }
      }
  }

Incorporate the handleSubmit method in your render process and utilize it as it now provides the required handler:

<form onSubmit={this.handleSubmit()} className="login-registration-form ion-padding">

Answer №2

Successfully linked the handleSubmit function to the class during initialization.

  constructor(props: any) {
        super(props);
        const errors: Errors = {};
        const values: Values = {};
        this.state = {
            errors,
            values
        };
        this.currentPasswordProvided = false;
        this.passwordValidated = false;
        this.completeValidation = false;
        this.emailAddress = '';
        Reset.history = this.props.history;
        this.handleSubmit=this.handleSubmit.bind(this) //<------ Critical to bind it to the class because upon submission, the handler becomes unmounted, resulting in undefined "this" in the handleSubmit.
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for extracting the two characters following a space in a string with or without the use of regex

How can I extract only the initials of 2 characters after spaces? See the code snippet below: const name = "John Peter Don"; const result = name.match(/\b(\w)/g).join(''); console.log(result)// JPD->> i want only JP ...

Discovering a particular element involves iterating through the results returned by the findElements method in JavaScript

I am attempting to locate and interact with a specific item by comparing text from a list of items. The element distinguished by .list_of_items is a ul that consists of a list of li>a elements. I am uncertain about how to transfer the determined elemen ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

Monitor changes in the visible price range in lightweight-chart

Is there a way to detect when the visible price range changes in lightweight-chart, similar to how the timeScale's visible time range change can be detected through subscribeVisibleTimeRangeChange? I couldn't find anything related in the document ...

ERROR: Unable to call function getTime in Typescript

While working on my function in Typescript, I encountered an issue with two sets of data in the database - date and time, both expecting strings. When users select a date, I trigger a POST request to set the time for them. To handle this scenario, I creat ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

What is the best way to acquire an ID that is generated dynamically?

Being new to javascript and ajax, I am facing a challenge. I have a while loop with 2 buttons, both of which seem to function correctly, except for one small issue... The product-id is only being passed for the first or last element in the loop. How can I ...

Stop Antd Modal from automatically scrolling to the top

At the moment, I'm utilizing Ant Design (v4.22.8) and Next.js (v12.3.4) in my project. One issue I've encountered is with a Modal component that activates when a button is clicked. Instead of overlaying the current content on the screen, the moda ...

javascript highchart image carousel

I am currently working on a visual chart project using the JavaScript library highchart. After setting up my chart with some dummy data, I am looking to incorporate functionality that allows for triggering an image slide based on the chart data. Specific ...

Utilizing jsPDF and html2canvas in a Vue.js application (no webpack involved)

I've been working on a feature within a Vuejs project that allows users to export a PDF containing specific Vuejs components by clicking a button. Everything was going smoothly until I encountered an issue. After npm installing the jsPDF and html2canv ...

Please provide the text input for the specified version numbers (1.1, 1.2, 3.0, etc.)

I'm currently working on a form that includes a section for searching by version number: <label class="formLabel">Version</label> <html:text property="valueVersion" styleClass="value" tabindex="11"/> <br/& ...

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

Issue with Jquery's .html() function not functioning properly when trying to select HTML

I am currently working on a piece of code that looks like this: $price = $(element) > $('.main_paket_price').attr('name'); alert($price); Basically, I am trying to select an element inside element which has the class main_paket_pri ...

JS client-side form validation involves communicating with the server to verify user input

I currently have an HTML form that is being validated on the client side. Below is a snippet of the code: <form id='myForm' onsubmit='return myFormValidation()'> ... </form> Now, I want to incorporate server-side valida ...

Webpage Text Animation

This is the visual representation of my webpage: https://i.stack.imgur.com/tYq34.png I am seeking to implement a uniform animation effect for the text "Carlos Qiano" and "Lorem Ipsum", similar to the link below: https://i.stack.imgur.com/XVnBS.jpg Note: ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

A ReferenceError was thrown because angular is not defined within the angular-moment.js script

After spending an hour trying to figure out what went wrong, I still can't solve this problem. I've searched on stackoverflow for answers, but nothing seems to be helpful. The issue arises when trying to integrate Moment js into my project. Che ...

Using (javascript:) within Href attributes

Recently, I've noticed some people including "javascript:" in the href attribute of an a tag. My question is: what is the purpose of this? Does it guarantee that clicking on the a tag directs the function of the click to JavaScript for handling, rathe ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

What is the best way to retrieve data from app.post within react.js?

//server.js app.post('/trip', function(req,res){ var params = "something"; getResult(params).then((db)=>{ // I am trying to access the variable called "db" in my App.js(React) file, but I am unsure of how to do so. res.s ...