Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get JSON data from fetch (react-native)

I'm writing small app for iPhone using react native. I'm trying to fetch JSON data from a website using fetch. Like in the example:

   function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  }
  throw new Error(response.statusText)
}

function json(response) {
  return response.json()
}


fetch('/users', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
}).then(status)
  .then(json)
  .then(function(json) {
    console.log('request succeeded with json response', json)
  }).catch(function(error) {
    console.log('request failed', error)
  })

Everything works fine but I need to use that data later. When I try to assign it to some variable in json function, I get "Request error" and after that get the data (correctly). What's the best practise to get that data and have it in some variable to use it later?

like image 912
Michał Zubrzycki Avatar asked May 05 '15 19:05

Michał Zubrzycki


People also ask

How to fetch data from a JSON file in a react app?

Fetch Data from a JSON File in a React App Introduction. Creating API mockups for local testing and development allows you to work in a faster development... Setting Up a Local JSON file. In a blank Create React App project, create a local JSON file named data.json inside the... Consuming Local JSON ...

What is the fetch API in React Native?

React Native provides the Fetch API for fetching data from remote servers and APIs. It’s quite similar to the browser APIs such as fetch () and XMLHttpRequest.

How to show data procurement in React Native?

We’ll cover the following options for fetching data in React Native: To show data procurement in React Native, we’ll construct a basic app that fetches a list of items from Coffee API. Moreover, we will use the NativeBase UI library for rendering our data to the client. In the end, your example app will look like this:

How to use useeffect in react for fetching data?

Now, let’s fetch our data. useEffect is a builtin hook that allows you to perform side effects in your React application such as fetching data. Next, inside the App () function, add the API_KEY and URL variables:


2 Answers

Firstly, as you know, each request returns a header and a body

When we use fetch a default response that is headers request. If we need to body of request, that's enough response.json()

return fetch(url,{
  method: 'POST',//GET and ...
  headers:{
      Accept: 'application/json',
      'Content-Type': 'application/json',
  },
  body: JSON.stringify({
      elm: "elm" //is fake
  })
 })
 .then((response)=>response.json()) //   <------ this line 
 .then((response)=>{
   return response ;
 });

And if the body of your request is html dom Just use this response.text()

And if you want to return your header no need to do anything, Just add this line .then((response)=>response.json())

like image 88
Mahdi Bashirpour Avatar answered Oct 19 '22 13:10

Mahdi Bashirpour


I did it like this. I displayed the response on console. You can store the response data in your state variable or in local storage as you want.

  doSignUp() {

     console.log("inside post api");
     fetch('your API URL', {
     method: 'POST',
     headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',

                },


      body: JSON.stringify({
      password: this.state.password,
      email:this.state.email,
      name: this.state.firstname,
      last_name :this.state.last_name,
      mobile:this.state.mobile,
      ssn:"2222222"

     })
      }).then((response) => response.json())
        .then((responseData) => {
                                 console.log("inside responsejson");
                                 console.log('response object:',responseData)

         }).done();
     }
like image 30
coderzzz18 Avatar answered Oct 19 '22 12:10

coderzzz18