I use React-Native request some data, here is my code:
fetch('https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json')
.then((response)=>{
return response.json()
})
.then((responseJSON)=>{
callback(responseJSON)
})
.catch((error)=>{
console.error(error);
})
.done()
I see the response
is a Response
object, and the json
function code is return this.text().then(JSON.parse)
, I'm confused that what is the parameter of theJSON.parse
? Is that the response
raw value? How can I get it?
The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
The fetch() method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.
To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.
Here's how you'd do what you want. In my case I wanted to manually parse the JSON because a certain character (\u001e) is improperly parsed by the in-built JSON parser.
Change from:
fetch(url)
.then(response => response.json())
.then((data) => {
data....
to:
fetch(url)
.then(response => response.text())
.then((dataStr) => {
let data = JSON.parse(dataStr);
data...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With