Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'TypeError: NetworkError when attempting to fetch resource' on form submit ReactJS

I tried to fetch some data from my API with Cross-Origin enabled but got this error.
Same thing with JSONPlaceholder (an online REST API for testing) using an example they provide :

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

Both requests (JSONPlaceholder and my API) work fine using Insomnia (a REST client), so my guess is that the problem is in my React application (16.13.1).

EDIT

After some tests, it seems that the error only occurs when calling the fetch function from a <form>, here are some details :

handleSubmit = () => {
   fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
}
<form onSubmit={this.handleSubmit} >
    <button type="submit">FETCH</button>
</form>

Thanks.

like image 214
adxl Avatar asked Apr 23 '26 09:04

adxl


1 Answers

I managed the reproduce your error. It seems like the network request is stopped when the page reloads. You could add a simple event.preventDefault to stop the reload until the fetch finishes and then reload the page.

handleSubmit = (event) => {
  event.preventDefault()
  fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then((response) => response.json())
    .then((json) => {
      console.log(json)
      window.location.reload()
    })
}

And of course you can also not reload the page at all for a better user experience :)

like image 182
Adam Jeliński Avatar answered Apr 25 '26 23:04

Adam Jeliński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!