jeudi 16 septembre 2021

React How to re-render state hook with useEffect and useCallback?

I apologize for asking this question. I've read many posts on how to re-render the state but I still can't figure it out. I'm too noob :( I can get things to work with useRef, but I'd like to learn how to update state with useEffect and useCallback. My database fetch requires a second click to fire because setState is asynchronous. Neither of my useEffect/useCallback updates state :( useEffect is firing, I'm getting the console log.

export function Form() {
    const[inputKey, setInputKey] = useState("");
    const inputKeyRef = useRef();

    const [keyValid, setKeyValid] = useState(false);
    useEffect(() => {
        console.log("keyValid:", keyValid)
    }, [keyValid])

    const [keyAuthentic, setKeyAuthentic] = useState(false);
    useEffect(() => {
        console.log("keyAuthentic:", keyAuthentic)
    }, [keyAuthentic])

    const updateKeyValid = useCallback(
        () => setKeyValid(true),
        [keyValid, setKeyValid]
    )

    const submit = e => {
        e.preventDefault();
        if ( !inputKeyRef.current.value.length < 12 || !inputKeyRef.current.value.length < 20 ) {
            setKeyValid(true) // not updating state
            updateKeyValid(); // not updating state
        }

        if ( keyValid === true ) { // state not true if keyValid(true)
            db.collection("users").doc(inputKey).get().then((doc) => {
                if (doc.exists) {
                    setKeyAuthentic(true)
                    console.log(doc.data())
                }
            });
        }
    };

    return (
        <div className="form__submit">
            <Button type="submit" onClick={submit}}>Submit</Button>
        </div>
    )
}

export default Form

Aucun commentaire:

Enregistrer un commentaire