Home > Software design >  React get and post form data api. Too many re-renders
React get and post form data api. Too many re-renders

Time:09-27

I am creating common user profile in React with getting and posting data with api. For getting data from form I am using useState Hooks but now I am having error "Too many re-renders. React limits the number of renders to prevent an infinite loop."

The Code:

    const [data, setData] = useState([{}]);

    const [name, setName] = useState('');
    const [ic, setIc] = useState('');
    const [dic, setDic] = useState('');
    const [address, setAddress] = useState('');
    const [city, setCity] = useState('');
    const [postalCode, setPostalCode] = useState('');
    const [web, setWeb] = useState('');
    const [telephone, setTelephone] = useState('');
    const [vatPayer, setVatPayer] = useState('');

  useEffect(() => {
    fetch(`${Url}subject/get`, {
        method: "GET",
        headers: {
             'Accept': 'application/json',
             'Content-Type': 'application/json',
             'Authorization': `Bearer ${authManager.getToken()}`}
    })
        .then(response => response.json())
        .then(json => setData(json))
        .catch(err => console.log(err));
  }, []);


const submit = async (e) => {
    e.preventDefault();

    const request = await fetch(`${Url}subject/update`, {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authManager.getToken()}`
        },
        body: JSON.stringify({
            "name": name,
            "ic": ic,
            "dic": dic,
            "address": address,
            "city": city,
            "postal_code": postalCode,
            "web": web,
            "telephone": telephone,
            "vat_payer": vatPayer
            })
    });

    const response = await request.json();


    if(request.status === 200)
    {
        Swal.fire({
            title: 'Updates',
            text: response.message,
            icon: 'success'
        });
    }

    if (request.status === 401)
    {
        Swal.fire({
            title: 'Error',
            text: response.message,
            icon: 'error'
        });
    }
};

Form code is to large so i post just piece:

    <Row>
        <Col xs={12} xl={8}>
            <Card border="light" className="bg-white shadow-sm mb-4">
                <Card.Body>
                    <h5 className="mb-4">Test</h5>
                    <Form onSubmit={submit}>
                        <Row>
                            <Col md={12} className="mb-3">
                                <Form.Group id="name">
                                    <Form.Label>Name</Form.Label>
                                    <Form.Control onChange={e => setName(e.target.value)} required type="text" placeholder="name" value={data.name} />
                                </Form.Group>
                            </Col>
                        </Row>
                           <Row>
                                <Col md={6} className="mb-3">
                                    <Form.Group id="dphRadios">
                                        <Form.Check
                                            defaultChecked
                                            type="radio"
                                            defaultValue="neplatce"
                                            label="Neplátce DPH"
                                            name="platcedph"
                                            id="neplatceRadio"
                                            htmlFor="neplatceRadio"
                                            onBlur={setVatPayer(0)}
                                            checked={data.vat_payer == 0 ? true : false}
                                        />

                                        <Form.Check
                                            type="radio"
                                            defaultValue="platce"
                                            label="Plátce DPH"
                                            name="platcedph"
                                            id="platceRadio"
                                            htmlFor="platceRadio"
                                            onBlur={setVatPayer(1)}
                                            checked={data.vat_payer == 1 ? true :false}
                                        />
                                    </Form.Group>
                                </Col>
                            </Row>

CodePudding user response:

The onBlur handlers are immediately invoked. Use onBlur={() => setVatPayer(0)} instead of onBlur={setVatPayer(0)}.

<Form.Group id="dphRadios">
  <Form.Check
    defaultChecked
    type="radio"
    defaultValue="neplatce"
    label="Neplátce DPH"
    name="platcedph"
    id="neplatceRadio"
    htmlFor="neplatceRadio"
    onBlur={() => setVatPayer(0)}
    checked={data.vat_payer == 0}
  />

  <Form.Check
    type="radio"
    defaultValue="platce"
    label="Plátce DPH"
    name="platcedph"
    id="platceRadio"
    htmlFor="platceRadio"
    onBlur={() => setVatPayer(1)}
    checked={data.vat_payer == 1}
  />
</Form.Group>
  • Related