Recommand · October 14, 2021 0

Api calls infinite loop

I have some input fields and if one of them is updated I need to send all the data to the backend using api call. For the Send button, I created a specific component and added onClick method here with api call. In the deps of useCallback I need to put data object because if I don’t put it here, then I can’t get the data changed. But this is causing infinite loop and I tried to use specific property only, and then, after clicking save button, if I change checkbox value, is calling API without pressing Send button.

My code is like this:

const ParentComponent = () => {

const data = {
    id: 1,
    name: 'Person 1',
    lastName: 'Person LastName',
    address: 'PersonAddress'

            <input type="text" value={} />
            <input type="text" value={data.lastName} />
            <input type="text" value={data.address} />
                My Value
            <Child data={data} />

export default ParentComponent;

const Child = (data) => {

 const handleSubmit = useCallback(() => {
const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ })
    fetch('', requestOptions)
        .then(response => response.json())
        .then(data => console.log(data));
 }), [data];
    return (
        <button onClick={handleSubmit}>Send</button>

Note: I haven’t include handleCheckboxChange