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

Is it possible to access dl, dt, or dd tags based on their roles within the testing library?

Is there a way to use the testing library to specifically target the dd tag based on its role? <dl> <dt>ID</dt> <dd>123456</dd> </dl> I attempted: screen.getByRole('term', { name: 'ID' }) as wel ...

Ways to send a POST variable to PHP without refreshing the webpage

Is there a way to pass a simple variable from a text-box on a different page to PHP without reloading it? I've been informed that Ajax is required for this task, but I'm unsure of how to go about implementing it. Can someone provide me with a sam ...

Utilize npm node to dynamically adjust screen resolution

Currently developing a game using electron. I'm experiencing FPS drops when running it in full-screen mode. To improve the game's performance, I need to change the screen resolution programmatically. My current resolution is 1280x800, but I would ...

Is Validators.required a necessity in Angular 2?

Is there a way to dynamically require a form field based on conditions? I created a custom validator, but the conditional variables passed to it remain static. How can I update these conditional values within the custom validator function? Is it possible t ...

JS is programmed to automatically redirect the user after they have clicked on a div element and a

I'm having trouble with this code that is supposed to redirect a user after they click on the div and then the next button. It's not working for me :( Here is the code I am using: $("a.xxx").click(function() { $(this).toggleClass("yyy"). ...

The integration between React hook form and reactstrap input components is not functioning properly

Having an issue with react-hook-form and reactstrap. The component List.jsx is causing trouble: import { useContext, useEffect } from "react"; import { ListContext, ADD_LIST } from '../providers/ShoppingListProvider'; import { Link } from "react- ...

The state is accurate despite receiving null as the return value

I'm feeling a bit lost here. I have a main component that is subscribing to and fetching data (I'm using the redux dev tools to monitor it and it's updating the state as needed). In component A, I am doing: public FDC$ = this.store.pipe(sel ...

Error: JSON parsing error encountered due to an unexpected token 'U' while trying to read a file with

Currently, I am utilizing Node.js version 12.14.1 and encountering a problem while attempting to parse a JSON file that includes the \U0001f970 character. The file's content that needs to be read and parsed is as follows: {"randomKey": ...

I'm having trouble understanding the distinction between this.query and this.query.find(). Can you explain the difference to me?

Currently, I am working on a MERN tutorial where I am developing a full E-commerce application. This is the class that handles querying and various other tasks. constructor(query, querystr) { this.query = query; this.querystr = querystr; con ...

Ensure that data is not cached after the page is refreshed at regular intervals of x seconds

In the process of developing a news app, I have implemented a feature where a div with the class .new_feed is refreshed every 10 seconds to fetch new updates. However, I encountered an issue where if a new feed appears in the .new_feed div and is not cli ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Why does Vue 3 refuse to refresh an <img> element, while it successfully refreshes all other components within the same component?

In my current Vue project, I have set up multiple link cards (<a class='card'></a>) inside a "deck" container (<div class='deck'></div>). The implementation for these elements is relatively straightforward: <s ...

Leverage the object imported from the global <script> tag within a React component

I am currently attempting to incorporate a PayPal button into my React project. As per the instructions provided in PayPal's developer documentation, I have to include <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"& ...

Tips for updating a boolean value in a JSON file with a button in Angular and TypeScript

Can someone guide me on how to create a function in my table-viewer.component.ts file that can update the status from "false" to "true" in a JSON file when a user clicks the cancel button? The JSON file has the following information. db.json "firstN ...

Convert epoch time to HHMM format using JavaScript

I have a specific variable that stores epoch time data. My goal is to showcase the time information in HHMM format. Below you can find the code I am currently using; function convertEpochTimeToDateObj(epoch_time) { var utcSeconds = epoch_time; va ...

Angular 4 Filtering Pipe: Simplify Data Filtering in Angular

Attempting to replicate AngularJS's OrderBy feature. Working with an array like this, I am aiming to filter the cars by their car category. [ { "car_category": 3, "name": "Fusion", "year": "2010" }, { "car_category": 2, "na ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

Typescript: The property 'userId' is not found within the 'unknown' type

For my rxJS practice in Typescript, I wrote the following simple code. import fetch from 'node-fetch'; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from &apo ...

Extract CSS from Chrome developer tools and convert it into a JavaScript object

Recently, we have started incorporating styles into our React components using the makeStyles hook from Material-UI. Instead of traditional CSS, we are now using JavaScript objects to define styles. An example of this is shown below: const useStyles = ma ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...