javascriptreactjsnext.jsreact-hooksonsubmit

React.js onSubmit addNewUser is not a function


Why addNewUser is not a function ?

TypeError: addNewUser is not a function

Here is the problem, when i complete my form and click save show addNewUser is not a fuction.

const onSubmitHandler = (e) => {
    e.preventDefault();

// Here the problem when i complete my form and click save show addNewUser is not a fuction. 

    addNewUser({
        id: Math.round(Math.random() * 100),
        name,
        age,
        phone,
        address,
        type,
    });
    setName('');
    setAge('');
    setPhone('');
    setType('');
    setAddress('');
    closeModal();
};
    return ( 
        <Form onSubmit={onSubmitHandler}>
        <Form.Controller>
            <label htmlFor="name">Name</label>
            <input type="text" id="name" placeholder="Enter Your Name" value={name} onChange={(e) => setName(e.target.value)}></input>
        </Form.Controller>
        <Form.Controller>
            <label htmlFor="age">Age</label>
                <input type="text" id="age" placeholder="Enter Your Age" value={age} onChange={(e) => setAge(e.target.value)}></input>
        </Form.Controller>
        <Form.Controller>
            <label htmlFor="phone">Phone</label>
            <input type="text" id="phone" placeholder="Enter Your Phone" value={phone} onChange={(e) => setPhone(e.target.value)}></input>
        </Form.Controller>
        <Form.Controller>
            <label htmlFor="address">Address</label>
            <input type="text" id="address" placeholder="Enter Your Address" value={address} onChange={(e) => setAddress(e.target.value)}></input>
        </Form.Controller>
        <Form.Controller>
            <label htmlFor="type">Type</label>
            <input type="text" id="type" placeholder="Enter Your Type" value={type} onChange={(e) => setType(e.target.value)}></input>
        </Form.Controller>
        <Row>
            <Button type="submit">Save</Button>
            <Button type="reset">Reset</Button>
        </Row>
    </Form>
    );

Solution

  • Your question is missing much needed data, however after inspecting you GitHub repo I believe I've understood your issue.

    The AddUser is used in two places.

    App
     └ Modal
       ├ AddUser (1)
       └ Overlay
         └ AddUser (2)
    

    You pass the addUserHandler function correctly to the first instance of AddUser (1). But since children isn't used in Modal that instance isn't rendered. Instead the second instance of AddUser is rendered. For this instance you don't pass the addNewUser property. Hence it gives you the TypeError: addNewUser is not a function error.

    Reference: https://github.com/HassanFathy10/React.app/blob/a8cd6f19c46d0f545bfcf191d3348a9c13eb5ecc/src/App/App.js