3

I want to reuse some code that retrieves data from an API for two apps. One is an iOS app using React Native. The other one is a website using React.js.

I initially coded the class that retrieves data from an API when I built the iOS app. Thus, I used the fetch method available in React Native.

Unfortunately, there isn't such a method in React.js. My best option if I want to reuse my code is to abstract the call of the React Native's fetch method by creating a class HTTPRequests with a method fetch which will call the React Native's fetch method or the '$.get' method depending on the lib used by the project: React.js or React Native.

My question is the following: How can I detect the using of React.js or React Native in my project. My first idea is to detect if my JS code is executed through RCTRootView engine or a browser. But I've no idea how to accomplish this.

Any suggestion?

Thanks!

1
  • 2
    There are libraries that implement the fetch API in a browser, for example: github.com/github/fetch . Commented Jul 20, 2015 at 18:13

2 Answers 2

3

My suggestion would be to move shared logic into separate module (bower, npm, ES6), generalize the way you request data through fetch polyfill, and never ever bother with detecting React/React.native in your project. JS code detection will make your code unnecessary complicated and hard to support when new versions of React/React.native will come up.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes you're right. I finally managed to not have to create two cases depending which library I'm using.
I'm curious on how you created the shared files? You use browserify?
@AndyB my rule of thumb would be a separate npm package, you could even use local dependencies docs.npmjs.com/files/package.json#local-paths in your package.json with npm 2.0, I would also suggest linklocal package for development usage
@EugeneSafronov, cheers!! I won't have any problems with the exports in the browser? I.e. module.exports = MyModuleName;
@AndyB in the browser you will need either browserify or webpack. They both understands node's export style or modules API (with use of babel)
|
2

I have successful experience of building a cross-platform application with React and React Native using the platform-specific extensions feature of React Native. I've just described how I structured the code in order to achieve that in a blog post Code sharing between React and React Native applications

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.