Technoarch Softwares - ReactJS: Handle onChange api call when user stops typing

ReactJS: Handle onChange api call when user stops typing

  • When we have Input Fields which have to fire api requests on change we always tend to fire multiple api requests.

  • We can cancel the api request on duplicate api calls by using cancelToken. Or we can use clearTimeout and setTimeout

Declaring Global Variables 

We need to declare a time out interval that will run our  setTimeout function.

const WAIT_INTERVAL = 1000;  

We can declare event code for ‘enter’ if the user wants to fire the api on keypress

const ENTER_KEY = 13;

Implementing on TextField 

import React, { Component } from 'react';

import TextField from 'components/base/TextField';
 

const WAIT_INTERVAL = 1000;

const ENTER_KEY = 13;

export default class TextSearch extends Component {

    constructor(props) {

        super();

        this.state = {

            value: props.value

        };

    }

 

    componentWillMount() {

        this.timer = null;

    }

 

    handleChange(value) {

        clearTimeout(this.timer);

        this.setState({ value });

        this.timer = setTimeout(this.triggerChange, WAIT_INTERVAL);

    }

 

    handleKeyDown(e) {

        if (e.keyCode === ENTER_KEY) {

            this.triggerChange();

        }

    }

 

    triggerChange() {

        const { value } = this.state;

        this.props.onChange(value);

    }

 

    render() {

        const { className } = this.props;

        return (

            <TextField

                className={className}

                placeholder={l('Search')}

                value={this.state.value}

                onChange={this.handleChange}

                onKeyDown={this.handleKeyDown}

            />

        );

    }

}            


So what this code does is when the user stops typing triggerChange is fired where you can place your api. 

Whenever the user presses a key handleKeyDown function is called and clearTimeout is called and setTimeout is again initialized with  WAIT_INTERVAL initial value.

0 Comments:

Leave a Comments

Your email address will not be published. Required fields are marked *