Yabaz Thampi
Yabaz Thampi

Reputation: 82

Export JSON fetch React Native

I am exporting JSON by fetch from the URL. I think I have a binding issue if take from local data file working I'm not completely sure on how I should proceed to bind my function.

Data.js

const Json = require('./one.js'); // not working or  const Json = require('./two.json'); // working 

export default Json;    

one.js

function getvals(){
    return fetch('http://xxxxxx')
   .then((response) => response.json())
   .then((json) => {
     return json.products;
   })
   .catch((error) => {
     console.error(error);
   });
  }
  
  getvals().then(response => response);

two.json

 [{"id":"1","category":"kkk","title":"sss"}]

Upvotes: 0

Views: 427

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Nothing in one.js exports anything. With CommonJS-style modules, you export something by assigning it to a property on exports (or by reassigning the exports variable entirely).

But note that since what you're getting is only available asynchronously, other modules may request one.js's default export before the asynchronous process has completed. The usual solution to that is export the promise from fetch:

module.exports = fetch('http://xxxxxx')
    .then((response) => {
       if (!response.ok)  {
           throw new Error("HTTP error " + response.status);
       }
       return response.json();
    })
    .then((data) => {
        return data.products;
    });

Also note that you need to check for HTTP success (the footgun in the fetch API) and you don't want to hide errors; let the users of the module know if the fetch fails.

Code using that would need to use the promise, e.g.:

require("./one.js")
.then(data => {
    // ...use the products...
})
.catch(error => {
    // ...handle the fact the fetch failed and the data won't be coming...
});

I don't know the React Native ecosystem, but if you can to switch to JavaScript modules ("ESM" = ECMAScript Modules) instead (and if you want to), someday you'd be able to use a new feature called top-level await. The V8 engine has it (behind a flag), presumably JavaScriptCore will at some stage. That would let you suspend module evaluation until the fetch completed, and directly export the result:

// With top-level `await` in an ESM module
export default await fetch('http://xxxxxx')
    .then((response) => {
       if (!response.ok)  {
           throw new Error("HTTP error " + response.status);
       }
       return response.json();
    })
    .then((data) => {
        return data.products;
    });

Modules using it would be able to get the products directly:

import products from "./one.js";

If you're using Webpack (again, I don't know the React Native ecosystem), it has experimental support for it, too.

Upvotes: 1

Related Questions