V
V
Vladimir2022-02-21 10:30:03
JavaScript
Vladimir, 2022-02-21 10:30:03

How to update state to avoid recursion?

Hello. I encountered a violation 200+ error, I decided to fix debounce - I need to call it once, I do it, but I get an error that it is impossible to get id from undefined. I'm trying to get id from prevMessages and messages - they are states:

const debounce = (func, wait) => {
        let timeout;
        return (() => {
            if (timeout) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(() => func(), wait)
        })()
    }

    const changeHandler = (e) => {
        if(e.target.scrollTop < 1) {
            const msgID = prevMessages.length ? parseInt(prevMessages[0].id) : parseInt(messages[0].id); // prevMessages and messages = useState([])
            console.log(msgID);
            socket.emit('getPrevMessages', {roomId, msgID});
            e.target.scrollTo(0, e.target.querySelector('.direct-chat-msg:nth-child(20)').offsetTop);
            //e.stopPropagation();
        }
    }
    const debouncedChangeHandler = useCallback((e) => debounce(() => changeHandler(e), 250), []); // Если попробовать [prevMessages, messages] - получаю рекурсию и зависание страницы


Please tell me how to implement it correctly? I hang the handler on the block's scroll.

Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question