React.js: Failed to fetch error when sending requests to the server

I'm trying to send a request for CRUD operations to the back-end via fetch(). Here is a code snippet:

// Добавляет новый объект
uploadAction(event) {
    event.preventDefault()
    const target = event.target;
    //let formData = new FormData();
    let newData = {
        data: {
            Email: target.emailSubmit.value,
            Age: target.ageSubmit.value,
        }
    };
    //formData.append('data', newData.data)

    let requestOptions = {
        headers: {
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }, 
        method: "PUT",
        //mode: 'cors',
        //body: formData,
        body: JSON.stringify(newData)
    }
    fetch(this.url + '/api/records', requestOptions)
    .then(response => response.json())
    .then(
        (result) => {
            alert("Perfect send data");
        },
        (error) => {
            alert(error.message);
        }
    )
    this.setState({
        editable: !this.state.editable,
        items: this.state.items
    })
    window.location.reload();
}

// Сохраняет изменения
saveAction(event, nameOfInputs, id) {
    event.preventDefault();
    let newData = {
        data: {}
    };
    //let formData = new FormData();
    let inputs = document.getElementsByName(nameOfInputs);
    inputs.forEach(
        input => {
            let key = input.id.split('|')[1];
            newData.data[key] = input.value;
        }
    )
    //formData.append('data', newData.data);

    let requestOptions = {
        headers: {
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }, 
        method: "POST",
        mode: 'cors',
        //body: formData,
        body: JSON.stringify(newData),
    }

    fetch(this.url + '/api/records/' + id, requestOptions)
    .then(function(response) {
        return response.json();
    })
    .then(
        (result) => {
            alert("Perfect edit data");
        },
        (error) => {
            alert(error.message);
        }
    )


    this.setState({
        editable: !this.state.editable,
        items: this.state.items
    })
    window.location.reload();
}

// Удаляет пользователя
deleteUser = (event, id) => {
    event.preventDefault();
    console.log(id);
    fetch(this.url + '/api/records/' + id, {
        headers: {
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }, 
        method:'DELETE'
    })
    .then(response => response.json())
    .then(
        (result) => {
            return alert('Perfect delete!');
        },
        (error) => {
            return alert('Error on delete ' + error.message);
        }
    )
    this.setState({
        editable: !this.state.editable,
        items: this.state.items
    })
    window.location.reload();
}

Problem:

Approximately every second request ends with a Failed to fetch error, but even if an error occurs, the add/edit/delete operation may work.

What I tried (in the code I commented //):

  1. Send data via the form
  2. change request types from POST to PUT and back
  3. .then(response => response.json() replaced with
.then(function(response) {
            return response.json();
        })
  1. I was looking for an answer in other topics: https://stackoverflow.com/questions/49477659/typeerror-failed-to-fetch-react-js https://stackoverflow.com/questions/56948938/react-fetch-failed-typeerror-failed-to-fetch-even-though-the-api-returns-dat

I attach a video of my actions leading to the error

Https://www.dropbox.com/s/shgsnpwk7ngzor4/2020-05-06%20at%2022-20-56.mp4?dl=0

P.S.: probably a problem it lies on the server side. It is a pity that I do not have access to it ((

Author: Егор Зенкин, 2020-05-06

1 answers

The problem seemed to be that the table simply wasn't redrawn during fetch(). I don't understand the logic very well, as I'm quite a beginner, and the solution may not be the most beautiful, but it works!

.then(
  (result) => {
      window.location.reload();
  }
)

I just reloaded the page when sending it successfully and everything worked.

 1
Author: Егор Зенкин, 2020-05-09 14:43:29