vendredi 29 janvier 2021

Use a prop function inside useEffect return: prop.function is not a function

I am currently trying to build an next.js app.

So what I want to do is passing a function to a component and call it with useEffect

I have the following component in order to change the props of the parents element. Therefore I pass the function from the parent like this:

<NumberInput name="height" update={manuelUpdate}></NumberInput>

The manuelUpdate function is a another props function from the actual parent:

const manuelUpdate = (name, value) => {
    props.update(name, value);
};

It works fine if I run the props.function with the onclick functions. However as soon as I try to use it in useEffect, it returns that the function is not a function. Maybe I am just thinking to complicated..

this is the component;

const NumberInput = ({ name, min = undefined, max = undefined, ...props }) => {
   
    const minInput = min !== undefined
        ? min
        : null;

    const maxInput = max !== undefined
        ? max
        : null;

    const [numb, setNumb] = useState(0);

    useEffect(() => {
        console.log(props.update)
    }, [numb]);

    const increaseNumb = () => {
        if (numb < maxInput || maxInput == null) {
            setNumb(numb + 1)
        }
        props.update(name, numb)
    };

    const decreaseNumb = () => {
        if (numb < minInput || minInput == null) {
            setNumb(numb - 1)
        }
    };

    const changeHandler = ({ e }) => {
        let n = parseInt(e.target.value)
        if (Number.isNaN(n)) {
            setNumb(numb)
        } else {
            setNumb(n)
        }
    }

    return (
        <div className={styles.def_number_input, styles.number_input}>
            <button onClick={decreaseNumb} className={styles.minus}></button>
            <input className={styles.quantity} name="quantity" value={numb} onChange={(e) => changeHandler({ e })}
                type="number" />
            <button onClick={increaseNumb} className={styles.plus}></button>
        </div>
    );
};

sorry in advance if my question is stupid or my code messy, I am still in the process of learning :D




Aucun commentaire:

Enregistrer un commentaire