React API fetch returning an empty object

Asked
Active3 hr before
Viewed126 times

8 Answers

objectreact
90%

state is updated asynchronously. If you want to see the updated state immediately after updating it, pass a second argument to setState function which is a callback function which runs after the state has updated,However, I'll need to save the fetched data into the state, but when I call it after saving it, it returns a empty object, that influences me to print the data to UI.,Find centralized, trusted content and collaborate around the technologies you use most.

state is updated asynchronously. If you want to see the updated state immediately after updating it, pass a second argument to setState function which is a callback function which runs after the state has updated

this.setState({
   api: data[0],
   loading: false
}, () => console.log(this.state))
load more v
88%

Pretag
 Pretag team - issue, fix, solve, resolve
72%

Even thought that the node (this.props.dir) in exist FB, the fetch returns an empty object like if I was fetching "foo" (non-existing node in the FB). The DB.update works exactly as expected...,@qwales1 I updated the code and not it doesn't set firebase to null, but it does almost the same as before. It just receives null instead of an empty object { }..,@Norfeldt I set up the same structure in a test DB and was able to fetch it. Is there another place (componentWillMount ?) that is setting that to an empty value? A call to this.syncDB maybe?

componentDidMount() {
   DB.fetch(`${this.props.dir}`, {
      context: this
   }).then(fetchdata => {
      console.log(fetchdata)
      if (_.isEmpty(fetchdata)) {
         const newNode = {};
         newNode[this.props.node] = this.state.value;
         DB.update(`${this.props.dir}`, {
               data: newNode
            })
            .then(this.syncDB)
      } else {
         this.syncDB
      }
   }).catch(error => console.error(error))
}
load more v
65%

I’ve been working with React Native lately, which uses the Fetch API for asynchronously fetching data from web services.,After some discussion, we decided that returning a null was the correct action for the API in this case. That meant that we would have to handle the null on the client side.,In this case, I kept adding console.log() statements further and further up the chain to try to understand where the error was coming from. Eventually, I arrived all the way up in the wrapper that we’d written for the Fetch API.

function _get(url) {
   return fetch(url, {
         headers: {
            Authorization: `Bearer ${this.accessToken}`,
         },
      })
      .then((res) => res.text())
      .then((text) => text.length ? JSON.parse(text) : {})
      .catch((error) => {
         throw error;
      });
}
75%

The example API returns a JSON object like this:,Uncontrolled Components,4. Components and Props

{
   "items": [{
         "id": 1,
         "name": "Apples",
         "price": "$2"
      },
      {
         "id": 2,
         "name": "Peaches",
         "price": "$5"
      }
   ]
}
load more v
40%

Synchronous and asynchronous actions,For most synchronous action creators, that is all we need to do.,Fetching data from an API

Pretag
 Pretag team - issue, fix, solve, resolve
22%

The same can be achieved by passing an array of arrays or an object literal to the constructor:,A Headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. This affects whether the set(), delete(), and append() methods will mutate the header. For more information see Guard.,Note: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

var myHeaders = new Headers();

myHeaders.append('Content-Type', 'text/xml');
myHeaders.get('Content-Type') // should return 'text/xml'
load more v
60%

Below is a quick set of examples to show how to send HTTP GET requests from React to a backend API using fetch() which comes bundled with all modern browsers.,This sends the same GET request again from React using fetch with the HTTP Content-Type header set to application/json., React + Fetch - HTTP DELETE Request Examples

This sends an HTTP GET request from React to the npm api to search for all react packages using the query q=react, then assigns the total returned in the response to the component state property totalReactPackages so it can be displayed in the render() method.

componentDidMount() {
   // Simple GET request using fetch
   fetch('https://api.npms.io/v2/search?q=react')
      .then(response => response.json())
      .then(data => this.setState({
         totalReactPackages: data.total
      }));
}
load more v

Other "object-react" queries related to "React API fetch returning an empty object"