Spying on the fetch API
In this section, we’ll use the Fetch
API to send customer data to our backend service. We already have an onSubmit
prop that is called when the form is submitted. We’ll morph this onSubmit
call into a global.fetch
call, in the process of adjusting our existing tests.
In our updated component, when the Submit button is clicked, a POST
HTTP request is sent to the /customers
endpoint via the fetch
function. The body of the request will be a JavaScript Object Notation (JSON) object representation of our customer.
The server implementation that’s included in the GitHub repository will return an updated customer
object with an additional field: the customer id
value.
If the fetch
request is successful, we’ll call a new onSave
callback prop with the fetch
response. If the request isn’t successful, onSave
won’t be called and we’ll instead render an error message.
You can think of fetch
as a more advanced form...