<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mihovil Kovačević on Medium]]></title>
        <description><![CDATA[Stories by Mihovil Kovačević on Medium]]></description>
        <link>https://medium.com/@mihovilkovaevi?source=rss-bd9961573538------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ws0RCo5iTRwFqI58aWqheg.jpeg</url>
            <title>Stories by Mihovil Kovačević on Medium</title>
            <link>https://medium.com/@mihovilkovaevi?source=rss-bd9961573538------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:38:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mihovilkovaevi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ways to pass objects between native and JavaScript in React Native]]></title>
            <link>https://medium.com/shoutem/ways-to-pass-objects-between-native-and-javascript-in-react-native-c3dcae7bf4f5?source=rss-bd9961573538------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3dcae7bf4f5</guid>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mihovil Kovačević]]></dc:creator>
            <pubDate>Mon, 27 Mar 2017 16:11:13 GMT</pubDate>
            <atom:updated>2017-04-28T08:54:48.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBajfagsRZPYS706H9FHbQ.png" /></figure><p>This is the second part of our story on how we built a <a href="https://github.com/shoutem/react-native-shopify">React Native bridge for Shopify’s</a> iOS and Android SDK. In the <a href="https://medium.com/shoutem/top-lessons-we-learned-while-building-a-react-native-bridge-library-bd6485cc6212#.cd3nk0k4q">first par</a>t, I described how to set up the project structure for the bridge library. With that out of the way, it’s time to write methods that will expose the native APIs to JavaScript. This article will be a bit longer than the first one. There’s a lot of ground to cover!</p><p>The <a href="https://facebook.github.io/react-native/docs/native-modules-ios.html">official documentation</a> explains the basics of native modules. But, sometimes you’ll need to handle more complex cases. For example, we had to pass most of Shopify’s data model, such as products and collections, to JavaScript. We also had to create native objects from ones we passed from JavaScript.</p><p>One such example was creating a native checkout from a collection of cart items. Since a lot can go wrong during a checkout, we also needed a way to handle native errors. We thought: how hard can this be?</p><p>But, we couldn’t find all the answers in the documentation, so we had to dig deeper. We learned a lot along the way, and I’m here to share this with you. This article lists recipes and best practices for various use cases you’ll encounter.</p><h3>Passing complex data structures from native to JavaScript</h3><p>The first challenging bridge method we implemented was getting a list of products. Both the iOS and Android SDK have custom models for products. The models have nested objects such as variants. SDK methods for fetching products all return these native objects. If you try to send them over the bridge, you’ll get an error.</p><p>A React Native bridge method works only with standard JSON types. These are strings, numbers, booleans, arrays and maps. You’ll need to convert native objects to structures that have only these types. For iOS, you’ll have to transform native objects to NSDictionaries. With Android, you’ll need WritableMaps and WritableArrays for objects and collections.</p><p>You could create these data structures on your own. One way is to create an empty dictionary and add an entry for each property of the native object. These objects can have dozens of properties and even nested objects. The manual approach can become cumbersome.</p><h3>Converting objects for iOS — the easy and hard way</h3><p>For iOS, we noticed that the SDK has a <em>JSONDictionary</em> method. At first, we thought that this was a method of all native objects. It turned out that the SDK had it as a helper method. It helped with serialization and deserialization when making calls to Shopify API.</p><p>There’s a high chance that the SDK you’re bridging will have a similar method. You might not see it in the documentation but try to find it by digging through the source files. The difference between using such a method and the manual way is outstanding:</p><pre>/**<br>  * This method adds options for variants the manual way. <br>  * The SDK’s JSONDictionary method doesn’t include them.<br>  */</pre><pre>- (NSArray *) getDictionariesForProducts:(NSArray&lt;BUYProduct *&gt; *)products <br>{ <br>  NSMutableArray *result = [NSMutableArray array]; <br>  <br>  for (BUYProduct *product in products) { <br>    NSMutableDictionary *productDictionary = [[<strong>product     <br>     JSONDictionary</strong>] mutableCopy]; </pre><pre>   NSMutableArray *variants = [NSMutableArray array]; <br>   for (BUYProductVariant *variant in product.variants) {        <br>     // A lot of code to create a dictionary for a variant <br>   } <br>   productDictionary[@”variants”] = variants; <br>   [result addObject:  productDictionary]; <br>  } <br>  return result;<br>}</pre><p>In the above example, you can see both approaches and a common pattern that we used. Where we could get the entire data structure that way, we used the <em>JSONDictionary</em> method. Where there was a missing implementation, we created a dictionary. Then we added all the entries we needed. You can use the pattern above in your own code.</p><p>When creating native objects from their JavaScript counterparts, the same principles apply. You get NSArrays and NSDictionaries in your native code. To convert them, first look for SDK specific methods. In our case, Shopify had a method to create a product variant from a dictionary. We used it to create a native cart object from an array of JavaScript cart items:</p><pre>- (BUYCheckout *) createCheckoutFromCart:(NSArray *)cartItems<br>{    <br>  BUYModelManager *modelManager = self.client.modelManager;                           </pre><pre>  BUYCart *cart = [modelManager insertCartWithJSONDictionary:nil]; <br>    <br>  for (NSDictionary *cartItem in cartItems) {          </pre><pre>    BUYProductVariant *variant = <strong>[[BUYProductVariant alloc]    <br>     initWithModelManager:modelManager       <br>     JSONDictionary:cartItem[@&quot;variant&quot;]]</strong>;        </pre><pre>    for(int i = 0; i &lt; [cartItem[@&quot;quantity&quot;] integerValue]; i++) {                  </pre><pre>      [cart addVariant:variant];        <br>    }    <br>  }     <br>  BUYCheckout *checkout = [modelManager checkoutWithCart:cart];      <br>  return checkout;<br>}</pre><p>I’ve bolded the part where the SDK creates an object for us. This a similar pattern to what we’ve seen in the previous example.</p><h3>Converting objects for Android and a few helper methods</h3><p>With the Android SDK things are a bit different. For most objects, we couldn’t find a method to get a dictionary we could send over the bridge. But, the pattern to convert a Java object to a WritableMap and vice versa is simple:</p><ol><li>Serialize the object to a JSON string. You can do this with the help of <a href="https://github.com/google/gson"><strong>Gson</strong></a>, a well-known library.</li><li>Create a new instance of JSONObject from the JSON string.</li><li>Create a new WritableMap instance.</li><li>Iterate through the keys of the JSONObject instance.</li><li>Check each value using the <strong><em>instanceof </em></strong>operator. If it’s a simple type, put it in the WritableMap instance. If it’s a JSONArray or another JSONObject, iterate through it.</li></ol><p>You’ll need recursive methods to convert JSON Arrays/Objects to Writable Arrays/Maps. We found a Gist online that had these methods, and used it in our code. Let’s see how this recipe plays out in practice. We’ll use it to convert a list of Product objects to a WritableArray.</p><p>The Shopify SDK already implements a helper method to convert a Product object to JSON:</p><pre>/** <br>  * @return A JSON representation of this object. <br>  */ <br>public String toJsonString() { <br>  return BuyClientUtils.createDefaultGson().toJson(this); <br>}</pre><p>Even if the SDK you use doesn’t have such a method, you can do it with Gson. It’s easy, as you can see from the implementation:</p><pre>public static Gson createDefaultGson() {             </pre><pre>  GsonBuilder builder = new GsonBuilder();<br>  return builder.create();    <br>}</pre><p>I’ve omitted the customization parts of the implementation. For some objects, you’ll need to help Gson out. This depends on the structure of the object. You can find more information in Gson’s documentation.</p><p>We convert a list of Product objects to a WritableArray by iterating through it. For each product, we create its WritableMap representation.</p><pre>private WritableArray getProductsAsWritableArray(List&lt;Product&gt;      <br>  products) throws JSONException {    </pre><pre>  WritableArray array = new WritableNativeArray();     <br>  for (Product product : products) {      <br>    WritableMap productMap = <strong>convertJsonToMap(new        <br>      JSONObject(product.toJsonString()))</strong>;        </pre><pre>   array.pushMap(productMap);    <br>  }     <br>  return array;  <br>}</pre><p>The <strong><em>convertJsonToMap</em></strong> method is the recursive converter I mentioned above. You can find its implementation on this Gist:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c565d266e7c10af45e88556957d2928f/href">https://medium.com/media/c565d266e7c10af45e88556957d2928f/href</a></iframe><p>You can also find implementations for other conversion methods. There’s four of them. They convert JSON Arrays/Maps to Writable Arrays/Maps and vice versa. Speaking of conversion in the opposite way, the recipe is the same, but in reverse.</p><p>Note that in this case, the input to native code will be a Readable and not a WritableArray. They are almost the same, except that a ReadableArray is for reading values, not writing. Here’s how we created a native Cart object from a ReadableArray of cart items:</p><pre>cart = new Cart();      <br>for (int i = 0; i &lt; cartItems.size(); i++) {        <br>  ReadableMap cartItem = cartItems.getMap(i);        <br>  ReadableMap variantDictionary = cartItem.getMap(&quot;variant&quot;);          </pre><pre>  int quantity = cartItem.getInt(&quot;quantity&quot;);        <br>  <strong>JSONObject variantAsJsonObject =    <br>   convertMapToJson(variantDictionary);</strong>       <br> <br>  <strong>ProductVariant variant = <br>   fromVariantJson(variantAsJsonObject.toString());</strong>         <br>  <br>  for(int j = 0; j &lt; quantity; j++) {            <br>    cart.addVariant(variant);        <br>  }      <br>}</pre><pre>private ProductVariant fromVariantJson(String json) {    <br>  return BuyClientUtils.createDefaultGson().fromJson(json,  <br>   ProductVariant.class);  <br>}</pre><p>The bulk of the work was to create ProductVariant objects. First, we created a JSONObject instance from a ReadableMap with the helper method. Then we extracted its underlying JSON string. Finally, we used Gson to create an object from this JSON string and a class descriptor. Actually, we used Gson through the SDK’s wrapper. You saw the implementation earlier.</p><p>You can see that for Android you don’t even need native SDK helpers. You can use a combination of Gson and the above-mentioned utility methods. To reuse them in many parts of your bridge, put them in a utility class.</p><h3><strong>Creating errors users can understand</strong></h3><p>Sometimes a bridge call can fail and an error object can contain a lot of useful data. It might be the only way to figure out what went wrong. A checkout on Shopify is one such example. A checkout error has a structure with deep nesting:</p><pre>{&quot;errors&quot;:<br>  {&quot;checkout&quot;:<br>   {<br>    &quot;email&quot;:[{<br>     &quot;code&quot;:&quot;invalid&quot;,<br>     &quot;message&quot;:&quot;is invalid&quot;,<br>     &quot;options&quot;:{}<br>    }], <br>    &quot;shipping_address&quot;:{<br>      &quot;country_code&quot;:[{<br>        &quot;code&quot;:&quot;not_supported&quot;,<br>        &quot;message&quot;:&quot;is not supported&quot;, <br>        &quot;options&quot;:{}<br>      }]<br>    },<br>    &quot;billing_address&quot;:{<br>      &quot;country_code&quot;:[{<br>        &quot;code&quot;:&quot;not_supported&quot;, <br>        &quot;message&quot;:&quot;is not supported&quot;,<br>        &quot;options&quot;:{}<br>      }]<br>    }<br>   }<br>  }<br>}</pre><p>With iOS, there’s a standard way of rejecting a promise:</p><pre>if (error) {            <br>  return reject(<br>    [NSString stringWithFormat: @&quot;%lu&quot;, (long)error.code],    <br>    error.localizedDescription, <br>    error<br>  );        <br>}</pre><p>The <em>localizedDescription</em> and <em>userInfo</em> properties contain the error message. This works for simple cases. For errors such as the one from Shopify we saw above, you’ll get no useful description.</p><p>We solved this challenge by using a neat trick. Since the <em>userInfo </em>property of an error object is an NSDictionary, we serialized it to JSON. Then we sent this string to JavaScript:</p><pre>- (NSString *) getJsonFromError:(NSError *)error<br>{    <br>  NSError * err;    <br>  NSData * jsonData = [<strong>NSJSONSerialization <br>    dataWithJSONObject:error.userInfo</strong> options:0 error:&amp;err];     <br>  <br> return [[NSString alloc] initWithData:jsonData <br>   encoding:NSUTF8StringEncoding];<br>} </pre><p>In JavaScript land, we parsed it to get a message we could show to the user.</p><pre>const checkout = (cart) =&gt; {    <br>  return RNShopify.checkout(cart).catch((<strong>error</strong>) =&gt; {        <br>    throw new Error(<strong>getCheckoutError(error.message, cart)</strong>);      <br>});  </pre><pre><br>const getCheckoutError = (errorBody, cart) =&gt; {  <br>  if (!errorBody) {    <br>   return UNKNOWN_ERROR;  <br>  }   <br>  <br>  <strong>const errorObject = JSON.parse(errorBody); </strong>  <br>  const checkoutErrors = errorObject.errors.checkout;</pre><pre>  if (checkoutErrors.line_items) {    <br>   return getLineItemsErrorMessage(checkoutErrors.line_items, cart);       <br>  }   <br>  return getErrorMessageFromCheckoutObject(checkoutErrors);<br>};</pre><p>On Android, we got the JSON error string straight from the SDK:</p><pre>// Sync the checkout with Shopify    buyClient.createCheckout(checkout, new Callback&lt;Checkout&gt;() {             </pre><pre>    @Override      <br>    public void failure(BuyClientError error) {  <br>      promise.reject(&quot;&quot;, <strong>error.getRetrofitErrorBody()</strong>);      <br>    }    <br>});</pre><p>In theory, we could’ve implemented error handling in native parts of the bridge. But, we would have to duplicate a lot of the business logic. Here’s where React Native and the bridge concept shine. Notice that we did very little on the native side. We passed raw data to the JavaScript realm. That’s all. There we concentrated all our error handling logic in one place.</p><h3>Closing thoughts</h3><p>Transformations between native objects and their JavaScript counterparts are not straightforward. There’s very little documentation available on this. For example, we had to dig through React Native’s source code to learn about Writable and Readable maps and arrays.</p><p>I hope that this article will shed some light on how to approach this problem. We‘ll find even better ways in the future. If you know any, leave a comment below.</p><p><strong>There are a few other points I’d like to highlight before we close the series:</strong></p><ul><li>Keep the native part of your module thin. Put all the business logic in the JavaScript part. An obvious advantage is code reuse. If you’re a JavaScript developer, this is your home turf. You’ll be able to use all the tricks and tooling that you have years of experience with. Most of the users of your bridge are also JavaScript developers. They’ll have an easier time understanding it.</li><li>Get to know the SDK and look for methods that’ll make your native code simpler. Use JavaScript to create a single entry-point and enhance the SDKs. Avoid reimplementing things.</li><li>Consider simplifying the API for your users. For example, the Shopify SDK has several methods for fetching products. We found it convenient to create a single method with optional parameters:</li></ul><pre>export default {  <br>  ...RNShopify,  <br>  getProducts: (page = 1, collectionId, tags) =&gt; {    <br>   if (collectionId) {      <br>    return RNShopify.getProductsWithTagsForCollection(page, <br>      collectionId, tags);    <br>   }    <br>   return tags ? <br>    RNShopify.getProductsWithTags(page, tags) <br>    :  <br>    RNShopify.getProductsPage(page);  <br>},</pre><p>All said and done, building a bridge for native SDKs is a rewarding experience. It also pays big dividends for its creators and users. We‘d like to see React Native bridges for all SDKs soon! Now let’s go and build something.</p><p>You can find our <a href="https://github.com/shoutem/react-native-shopify"><strong><em>React Native Shopify bridge</em></strong></a> on GitHub. Stay tuned for more stories!</p><p><strong><em>If you like what you read, please tap or click “♥︎” </em></strong><em>to help to promote this piece to others.</em></p><p><em>I work at </em><a href="https://new.shoutem.com/?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=dev_posts&amp;utm_content=bridge_library"><strong><em>Shoutem</em></strong></a><em> where I help creating tools to </em><a href="http://shoutem.github.io/?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=dev_posts&amp;utm_content=bridge_library"><strong><em>supercharge your React Native development</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3dcae7bf4f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shoutem/ways-to-pass-objects-between-native-and-javascript-in-react-native-c3dcae7bf4f5">Ways to pass objects between native and JavaScript in React Native</a> was originally published in <a href="https://medium.com/shoutem">Shoutem</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top lessons we learned while building a React Native bridge library]]></title>
            <link>https://medium.com/shoutem/top-lessons-we-learned-while-building-a-react-native-bridge-library-bd6485cc6212?source=rss-bd9961573538------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd6485cc6212</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[Mihovil Kovačević]]></dc:creator>
            <pubDate>Mon, 13 Mar 2017 19:18:19 GMT</pubDate>
            <atom:updated>2017-04-28T08:56:56.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChBbLhTHsn6TAm0CstHqQA.png" /></figure><p>This will be a two-part article. The first part focuses on the big picture and setting up the library structure. In the second part I’ll describe best practices for writing methods and passing objects.</p><p>As you build <a href="http://bit.ly/2poxM4q">React Native applications</a>, sooner or later you’ll want to use a 3rd party SDK. These usually come in iOS and Android variants. A bridge library lets you call native methods from both worlds, in Javascript.</p><p>You can find them for many popular SDKs. But, what if there is no bridge for the SDK you want to use, what do you do? Well, you’re out of luck. We recently had a similar situation in <a href="http://bit.ly/2poxM4q">Shoutem</a> when we wanted to integrate with Shopify.</p><p>I’ll show you how we went from zero to publishing a <a href="https://github.com/shoutem/react-native-shopify">library</a> that’s growing in popularity. We want to help you avoid all the pitfalls we met and make the process effortless.</p><h3>Sharing is caring</h3><p>You might be thinking why not plug the native SDKs in your application and call it a day. The official documentation on native modules for <a href="https://facebook.github.io/react-native/docs/native-modules-ios.html">iOS</a> and <a href="https://facebook.github.io/react-native/docs/native-modules-android.html">Android</a> covers this well. But, if you create a bridge library and use it in your application as a dependency:</p><ul><li>You’ll have an easier time maintaining it</li><li>If you open source it, others will give you feedback and even contribute. With our Shopify bridge, other developers are integrating Apple Pay</li><li>You’ll help the community, and you can’t put a price on that</li></ul><h3>Let’s start a library</h3><p>If you think that <em>react-native init </em>is a good place to start, you’re not alone. We thought that as well. But, it’s meant to scaffold an application, not a library, and won’t work for our purpose. Luckily, there is a great tool, called <a href="https://github.com/peggyrayzis/react-native-create-bridge"><em>react-native-create-bridge</em></a><em>, </em>that does exactly this. Run it, and your library is good to go. You can set up this structure on your own, but it’s a cumbersome and error-prone process. Before we continue, consider giving some appreciation to the author.</p><p>React Native changed the import format for its iOS headers in version 0.40. If you want to support both older and newer applications, use this neat trick for all React imports:</p><pre>// import RCTBridgeModule</pre><pre>#if __has_include(&lt;React/RCTBridgeModule.h&gt;)</pre><pre>#import &lt;React/RCTBridgeModule.h&gt;</pre><pre>#elif __has_include(“RCTBridgeModule.h”)</pre><pre>#import “RCTBridgeModule.h”</pre><pre>#else</pre><pre>#import “React/RCTBridgeModule.h” // Required when used as a Pod in a Swift project</pre><pre>#endif</pre><p>For local development, add the module as a dependency in your <em>package.json. </em>Then<em> </em>install it and run <em>react-native link. </em>Projects that’ll use it will do the same.</p><h3>Where to put the native SDK?</h3><p>You should let the consumer of your library decide. The bridge shouldn’t include it but assume that it can import its header files. For iOS, applications usually install SDKs with CocoaPods. You should change your header search paths to look for header files in the Pods directory. The image below shows how to do it. We’re in <em>node_modules/library_name/ios, </em>so we need to move up three times to get to the application root. Then we move down to the Pods folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*uXyhUYAhK-v9NUDWJRyItA.gif" /><figcaption>Header search path for SDKs that you install with CocoaPods</figcaption></figure><p>Including the SDK in the bridge is a bad idea. It introduces a transitive dependency, but that’s a topic for another story.</p><p>You can find our <a href="https://github.com/shoutem/react-native-shopify"><strong><em>React Native Shopify bridge</em></strong></a> on GitHub. Stay tuned for the second part!</p><p><strong><em>If you like what you read, please tap or click “♥︎” </em></strong><em>to help to promote this piece to others.</em></p><p><em>I work at </em><a href="http://bit.ly/2poxM4q"><strong><em>Shoutem</em></strong></a><em> where I help creating tools to </em><a href="http://shoutem.github.io/?utm_medium=social&amp;utm_source=medium&amp;utm_campaign=dev_posts&amp;utm_content=bridge_library"><strong><em>supercharge your React Native development</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd6485cc6212" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shoutem/top-lessons-we-learned-while-building-a-react-native-bridge-library-bd6485cc6212">Top lessons we learned while building a React Native bridge library</a> was originally published in <a href="https://medium.com/shoutem">Shoutem</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>