简体   繁体   中英

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

Issue was related to another problem. I was accidentally calling the component 2 times and forgot to adjust the parameters. CASE CLOSED

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM