Слайд 2CAN REACT DO THIS?
React itself doesn’t have any allegiance to any particular
way of fetching data.
In fact, as far as React is concerned, it doesn’t even know there’s a “server” in the picture at all.
React simply renders components, using data from only two places: props and state.
So therefore, to use some data from the server, you need to get that data into your components’ props or state.
You can complicate this process with services and data models (er, “build abstractions”) as much as you desire, but ultimately it’s just components rendering props and state.
Слайд 3HTTP LIBRARIES
Axios
Superagent
Fetch
Etc.
Слайд 4AXIOS
Axios is a very popular JavaScript library you can use to perform
HTTP requests, that works in both Browser and Node.js platforms.
Using Axios has quite a few advantages over the native Fetch API:
supports older browsers (Fetch needs a polyfill)
has a way to abort a request
has a way to set a response timeout
has built-in CSRF protection
supports upload progress
performs automatic JSON data transformation
works in Node.js
Слайд 6API
You can start an HTTP request from the axios object:
This returns a promise.
You can use async/await to resolve that promise to the response object:
Слайд 7API METHODS
For convenience, you will generally use the methods
axios.get()
axios.post()
axios.delete()
axios.put()
axios.patch()
axios.options()
Слайд 8API PROMISE SYNTAX
If you don’t want to use async/await you can use
the Promises syntax:
Слайд 9API GET PARAMETERS
With Axios you can perform this by using that URL
or
you can use a params property in the options:
Слайд 10API POST REQUESTS
Performing a POST request is just like doing a GET
request, but instead of axios.get, you use axios.post:
Слайд 11API ERROR HANDLING
Work with errors: