ReactJS delay onChange while typing

前端 未结 5 1299
臣服心动
臣服心动 2021-02-01 16:28

I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can\'t quite place my finger on how to

5条回答
  •  终归单人心
    2021-02-01 17:25

    Call every state update except the first time:

    Actually, I have the same issue but a little setTimeout could help me with a check ref for the first time mount:

    import React, {useState, useEffect, useRef} from "react";
    
    const Search = () => {
        const filterRef = useRef(); // use ref to call the API call all time except first time
        const [serpQuery, setSerpQuery] = useState('');
    
        useEffect(() => {
            let delayTimeOutFunction;
    
            if(!filterRef.current) {
                filterRef.current = true;
    
            } else { // componentDidMount equivalent
                delayTimeOutFunction = setTimeout(() => {
                    console.log('call api: ', serpQuery)
                }, 700); // denounce delay
            }
            return () => clearTimeout(delayTimeOutFunction);
        }, [serpQuery]);
    
        return (
           setSerpQuery(e.target.value)} />
        );
    };
    

提交回复
热议问题