<?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 Istvan Keri on Medium]]></title>
        <description><![CDATA[Stories by Istvan Keri on Medium]]></description>
        <link>https://medium.com/@istvanistvan?source=rss-3ba5eb362060------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TrkE7dFTMXTbmaBt.jpg</url>
            <title>Stories by Istvan Keri on Medium</title>
            <link>https://medium.com/@istvanistvan?source=rss-3ba5eb362060------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:10:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@istvanistvan/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[Modern  API Design with Apollo, GraphQL-Compose and Mongoose]]></title>
            <link>https://medium.com/swlh/modern-api-design-with-apollo-graphql-compose-and-mongoose-f67c0df060ea?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/f67c0df060ea</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 10:48:38 GMT</pubDate>
            <atom:updated>2020-02-20T05:18:33.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modern API Design with Apollo, GraphQL-Compose and Mongoose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TsT3qiE-usV6sHlYYxmxg.jpeg" /></figure><p>Bill Gates’ infamous first rule for automation states that automation applied to an efficient operation will magnify the <strong>efficiency</strong>. When it comes to API design there have been many attempts at code generation, transpiling and scaffolding of REST apis, yet due to the nature of REST, it has lead us to his second rule for automation - automation applied to an inefficient operation will magnify the <strong>inefficiency</strong>.</p><p>GraphQL Compose is great example of automation done right in an efficient system. Together with the mongoose plugin, it is a powerhouse, the holy grail of API architecture for those looking to accelerate speed to market. In essence, it allows for the entire GraphQL API to be generated from mongoose models, with some useful features such as query filtering, sorting, pagination .</p><p>To demonstrate how it works, let’s look at a simple use case. We have two mongoose models Users and Photos. Our Photos model has a reference to our Users model via the useRef property in our Schema.</p><pre>const photosSchema = new Schema({<br>  userId: String,<br>  userRef: [{ type: mongoose.Schema.Types.ObjectId, ref: &#39;Users&#39; }],<br>  film: {<br>    avatar: String,<br>    details: String,<br>    id: String,<br>    name: String,<br>  },<br>  camera: {<br>    avatar: String,<br>    details: String,<br>    id: String,<br>    name: String,<br>  },<br>  location: {<br>    coord: {<br>      lat: Number,<br>      lng: Number,<br>    },<br>    name: String,<br>    placeId: String,<br>  },<br>  caption: String,<br>  path: String,<br>  dateCreated: { <br>    type: Date, <br>    required: true,<br>    default: Date.now <br>  },<br>  dateUpdated: { <br>    type: Date, <br>    required: true,<br>    default: Date.now <br>  },<br>});</pre><pre>const Photos = mongoose.model(&#39;Photos&#39;, photosSchema, &#39;Photos&#39;);</pre><p>Let’s begin by importing our package, create the Type Composer using the composeWithMongoose function and pass in the Photos mongoose model as a parameter.</p><p>Create relations with other models by using the addRelation method on the Type Composer. Here we define the resolver and a projection to the ref field.</p><pre>const { composeWithMongoose } =  require(&#39;graphql-compose-mongoose&#39;);</pre><pre>.....</pre><pre>const customizationOptions = {};<br>const PhotosTC = composeWithMongoose(Photos, customizationOptions);</pre><pre>PhotosTC.addRelation(&#39;userDetails&#39;, {<br>  resolver: () =&gt; UsersTC.getResolver(&#39;findById&#39;),<br>  prepareArgs: {<br>    _id: source =&gt; source.userRef,<br>    skip: null,<br>    sort: null,<br>  },<br>  projection: { userRef: true },<br>})</pre><p>Next we create our Query and Resolvers. If you’ve used Mongoose before, you will notice your standard Model methods like “findById” being used to create graphQL resolvers.</p><pre>const photoQuery = {<br>  photoById: PhotosTC.getResolver(&#39;findById&#39;),<br>  photoByIds: PhotosTC.getResolver(&#39;findByIds&#39;),<br>  photoOne: PhotosTC.getResolver(&#39;findOne&#39;),<br>  photoMany: PhotosTC.getResolver(&#39;findMany&#39;),<br>  photoCount: PhotosTC.getResolver(&#39;count&#39;),<br>  photoConnection: PhotosTC.getResolver(&#39;connection&#39;),<br>  photoPagination: PhotosTC.getResolver(&#39;pagination&#39;),<br>}</pre><pre>const photoMutation = {<br>  photoCreateOne: PhotosTC.getResolver(&#39;createOne&#39;),<br>  photoCreateMany: PhotosTC.getResolver(&#39;createMany&#39;),<br>  photoUpdateById: PhotosTC.getResolver(&#39;updateById&#39;),<br>  photoUpdateOne: PhotosTC.getResolver(&#39;updateOne&#39;),<br>  photoUpdateMany: PhotosTC.getResolver(&#39;updateMany&#39;),<br>  photoRemoveById: PhotosTC.getResolver(&#39;removeById&#39;),<br>  photoRemoveOne: PhotosTC.getResolver(&#39;removeOne&#39;),<br>  photoRemoveMany: PhotosTC.getResolver(&#39;removeMany&#39;),<br>};</pre><p>Export out</p><pre>module.exports = { Photos, photoQuery, photoMutation};</pre><p>Import queries and mutations into a single file where you can build your schema. I have an index file in a folder called graphql in my project</p><pre>const { SchemaComposer } = require(&#39;graphql-compose&#39;);<br>const { photoQuery, photoMutation } = require(&#39;../models/Photos&#39;);<br>const { userQuery, userMutation } = require(&#39;../models/Users&#39;);</pre><pre>const capaSchemaComposer = new SchemaComposer();<br>capaSchemaComposer.Query.addFields(<br>  {...userQuery, ...photoQuery}<br>);</pre><pre>capaSchemaComposer.Mutation.addFields(<br>  {...userMutation, ...photoMutation}<br>);</pre><pre>const graphqlSchema = capaSchemaComposer.buildSchema();</pre><pre>module.exports =  graphqlSchema;</pre><p>With that you just created all your CRUD API operations.</p><p>Now you can import your schema into Apollo and start your server.</p><pre>const { ApolloServer } = require(&#39;apollo-server-express&#39;);<br>const graphqlSchema = require(&#39;./graphql/index&#39;);</pre><pre>const apollo = new ApolloServer({<br>  schema: graphqlSchema<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQRZqYSNkEsz6JaRy6ugsA.png" /></figure><p>Now navigate to the playground and explore your new fully typed queries and mutations</p><p><strong>Installlation Instructions</strong></p><pre>npm install apollo-server-express  # for Express or Connect</pre><pre>npm install graphql graphql-compose mongoose graphql-compose-mongoose --save</pre><p>Links:<a href="https://graphql-compose.github.io/"><br>https://graphql-compose.github.io/</a><br><a href="https://github.com/graphql-compose/graphql-compose-mongoose">https://github.com/graphql-compose/graphql-compose-mongoose</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f67c0df060ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/modern-api-design-with-apollo-graphql-compose-and-mongoose-f67c0df060ea">Modern  API Design with Apollo, GraphQL-Compose and Mongoose</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Suggestion Inputs with React Native, Typescript and Context API]]></title>
            <link>https://medium.com/swlh/custom-suggestion-inputs-with-react-native-typescript-and-context-api-aade4dcd5cb5?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/aade4dcd5cb5</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[user-interface-design]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 23:49:29 GMT</pubDate>
            <atom:updated>2019-12-12T07:06:48.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Suggestion Inputs with React Native, Typescript and Context API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eR981hdeU7teeIuOKo4keA.png" /></figure><p>The cursor suggests dialog between man and machine. There is an expectation to interact. Like an old friend, the computer waits patiently for our entry at the communication point. It blinks, we enter some characters. It blinks again, we repeat. We search, we calculate, we navigate, we pour over results.</p><p>Over the years Inputs have gotten smarter. They remember, they finish our sentences. We can touch them with our finger. They can no longer be contained to a single box nor a single screen. These widgets have evolved over the years through experimentation and careful planning by scientists know as UX designers.</p><p>Let’s consider the suggestion input on a mobile app. Let’s say we have two input fields labeled film and camera. As the user types into the first field, we’d like to see some results right away. There could potentially be hundreds of film stock in the result set, so how should that data be displayed? On a web viewport, a scrollable dropdown usually would suffice but small scrollable surfaces can be hard to navigate on a mobile device without a mouse. The correct approach is to display the picker on a new screen, wait for a selection, and navigate back to the form with the input pre-populated. In order to do this we need to design some components and manage state.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeN-nEO8CpWE%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeN-nEO8CpWE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeN-nEO8CpWE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c48a5b31c22fc5f58f5f1b50284295f4/href">https://medium.com/media/c48a5b31c22fc5f58f5f1b50284295f4/href</a></iframe><p>Our implementation will consist of 3 major components. A form, the auto complete component, and the state provider. We will be using Typescript in our react native implementation and React context api for state management. React’s context api offers us exactly what we need. We will use it to keep track of form state, view state, and hold references to our active API endpoints. Instead of using multiple screens we will use one screen component and show/hide components based on our view state.</p><p>Our Interface looks like this:</p><pre>interface AutoCompleteContext {<br>  editMode: boolean;<br>  setEditMode(delta: boolean): void;<br>  form: FormValues;<br>  setForm(delta: object): void;<br>  active: string;<br>  setActive(delta: string): void;<br>  activeUrl: string;<br>  setActiveUrl(delta: string): void;<br>}</pre><h3>State</h3><p><strong>editMode</strong> —Type Boolean. Keeps track of view state. There are two states on our view. When we’re interacting with an input and when we’re not</p><p><strong>form</strong> — An object that holds our form state. We will use this object to keep our inputs in sync. The auto complete input is mapped to the property of this object.</p><p><strong>active — </strong>The element we’re currently editing. In our case this will be set to the names of our input.</p><p><strong>activeUrl — </strong>The auto complete api endpoint Url.</p><p>We begin with a context set to null. In order to get the null context to work with typescript I found the following helper function useful.</p><pre>export const AutoCompleteContext = createContext&lt;AutoCompleteContext | null&gt;(null);</pre><pre>export const useAutoCompleteContext = (): AutoCompleteContext =&gt; {<br>   const context = React.useContext(AutoCompleteContext) || null;<br>   if (context === null) {<br>     throw new Error(&#39;Must be used within a Provider&#39;);<br>   }<br>   return context;<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEOnYx1MjPT2qBEt7KPUZw.png" /></figure><h3>View</h3><p>Here is our screen component. The provider wraps our Form component and our AutoComplete widget.</p><pre>export const UploadDetails: NavigationScreenComponent = () =&gt; {<br>  return (<br>    &lt;View style={styles.container}&gt;<br>        &lt;CapaAutoCompleteProvider&gt;<br>            &lt;UploadDetailsForm /&gt;<br>            &lt;CapaAutoComplete /&gt;<br>        &lt;/CapaAutoCompleteProvider&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p>The form component uses Formik. We use <strong>onChangeText </strong>to detect user interaction<strong>. </strong>As soon as the user starts interacting with a form input <strong>handleInput</strong> is called.</p><pre>// called from Formik&#39;s onChangeText</pre><pre>const handleInput = (e: string, type: string, apiUrl: string) =&gt; {<br>    suggestionsContext.setActiveUrl(apiUrl);<br>    suggestionsContext.setEditMode(true);<br>    suggestionsContext.setActive(type);<br>    const formState = {<br>        ...suggestionsContext.form,<br>        [type as string]: e,<br>    };<br>    suggestionsContext.setForm(formState);<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDqY-hM1rr9c9GCKcDtoDQ.png" /><figcaption>The Formik Form</figcaption></figure><h3><strong>Auto Complete Component</strong></h3><p>Our component for auto completion will consist of an Input and a FlatList.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bImXC5JurhywlO9rewIn5Q.png" /></figure><p>The input value is coming from the context provider. Remember how i mentioned that we will be mapping the form object onto two inputs? This is where that is happening. On onChangeText we call the <strong>handleInput</strong> function. handleInput will set our form state and call fetch on the api. We are using lodash to debounce the api calls to make sure we’re not making too many repeated calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0OB4EbbdonVakaG7qFydg.png" /></figure><p>You can see the code for the entire autocomplete component using the link below:</p><p><a href="https://gist.github.com/istvanskeri/7e5cae47844a6f4c1dc07eea6042d718">https://gist.github.com/istvanskeri/7e5cae47844a6f4c1dc07eea6042d718</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aade4dcd5cb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/custom-suggestion-inputs-with-react-native-typescript-and-context-api-aade4dcd5cb5">Custom Suggestion Inputs with React Native, Typescript and Context API</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who Dares Wins: Strictly Typed React Native With Redux]]></title>
            <link>https://medium.com/swlh/who-dares-wins-strictly-typed-react-native-with-redux-3d71b7360741?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d71b7360741</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 04:58:18 GMT</pubDate>
            <atom:updated>2019-09-02T06:08:53.890Z</atom:updated>
            <content:encoded><![CDATA[<h3>Who Dares Wins: Strongly Typed React Native Apps With Redux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsbT5Osli5yQhAJQCUgCZw.png" /></figure><p>On June 4, 2019 Expo dropped SDK 33, a highly anticipated release, with an exciting addition: type definitions. Sometime in early July I decided to upgrade my project to SDK33, then spent the last 2 weeks of July converting the react native app to TypeScript. Here in sunny Los Angeles, this TypeScript summer hasn’t been a cruel one. There are many advantages of using typed Javascript. TypeScript allows us, developers, to work with a more accessible, coherent codebase while reducing bugs that stem from incorrect variable assignments.</p><p>I began the migration by installing the typescript parser and linter packages. Did you know that ESLint now supports typescript? I’m currently using Typescript Version 3.5.3, ESLint with AirBnB and Prettier. You’ll need to install these libraries and plugins manually using npm. To configure ESLint I modified my .eslintrc.json file to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfGGNbsFwBzzbT3XBOqLxg.png" /></figure><p>TypeScript uses a config file called .tsconfig.json. Here you can define your rules for the parser.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;allowSyntheticDefaultImports&quot;: true,<br>    &quot;jsx&quot;: &quot;react-native&quot;,<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;esnext&quot;],<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;noEmit&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;module&quot;: &quot;ES6&quot;,<br>    &quot;strict&quot;: true,<br>  },<br>  &quot;includes&quot;: [&quot;./declaration.d.ts&quot;],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;<br>  ]<br>}</pre><p>The declaration.d.ts file is a file I added in order to import images using the import syntax vs the require function.</p><pre>import signInGfx from &#39;../assets/images/signIn.jpg&#39;</pre><p>You can read more about it here <a href="https://stackoverflow.com/questions/51100401/typescript-image-import">https://stackoverflow.com/questions/51100401/typescript-image-import</a></p><p>Next, I renamed all of the js and jsx files to ts and tsx. When you do this, you will be seeing lots of red lines in your editor for the new files which after all is a good sign that you editor is detecting the TypeScript errors and everything is working.</p><p>So after I got everything configured, I began to convert my redux files to typescript. I created a folder called types under each redux module folder. The module folders contain all my actions, reducers and action creators. I have 3 modules to convert Auth, Errors and S3.</p><p>In the types folder i created a type definition file called actions.ts. This file will hold the type interfaces for our redux actions. <a href="https://gist.github.com/istvanskeri/d43d11b53676501008d212760bb8b980">Here is an example</a> of the action type definitions for Auth actions that keeps track of user authentication state variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/121e8e9eaf12224ebe4b2af6fd5c4443/href">https://medium.com/media/121e8e9eaf12224ebe4b2af6fd5c4443/href</a></iframe><p>Once you have that, then in your reducer include the definition file and set the type of your action passed to the reducer function.</p><p>import { AuthActionTypes } from ‘./types/actions’;</p><pre>export default function(<br>    state = initialState, <br>    action: AuthActionTypes<br>) {<br>    switch (action.type) {<br>        case &#39;SET_AUTH_PENDING&#39;:<br>             return {<br>                 ...state,<br>                 authPending: true,<br>             };<br>...</pre><p>Now, moving onto action creators and thunk action creators. React and Thunk both come with their own dispatch type defs, to use them import it from redux-thunk and or react. After importing ThunkDispatch and Dispatch, you can now do the following to type the dispatch that’s being passed to your action creator.</p><p>dispatch: Dispatch&lt;AuthActionTypes | ErrorsActionTypes&gt;</p><p>dispatch: ThunkDispatch&lt;{}, {}, AuthActionTypes | ErrorsActionTypes&gt;</p><p>You can check out the action creators for the auth module here</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1ef117ddcd992ea9ec3ee2b0102c7a0/href">https://medium.com/media/c1ef117ddcd992ea9ec3ee2b0102c7a0/href</a></iframe><h3>React Components</h3><p>Now that redux is set up with Typescript, I started migrating the react components. Pass two generics to the components: props and state. Then you define the type definitions for each.</p><pre>export default class App extends React.Component&lt;Props, State&gt; {</pre><pre>...</pre><pre>// JSX return type in render<br>public render(): JSX.Element</pre><p>you can define the interfaces for each screen in a separate file or in the component file. Here are my interfaces for the login screen props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHES1BS1CMyZVuPjVR6V4Q.png" /></figure><p>Below is the typings for mapDispatchToProps and mapStateToProps and connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTx55tuoFpubksqaKMSB4w.png" /></figure><p>Libraries like redux form provide their own typings. Some libraries do not. If you find yourself using a library that does not have type definitions try to find the type support on Definitely Typed, a collection types created by the typescript community.</p><p><a href="https://github.com/DefinitelyTyped/DefinitelyTyped">GitHub - DefinitelyTyped/DefinitelyTyped: The repository for high quality TypeScript type definitions.</a></p><p><strong>React Navigation</strong></p><p>I’m using a navigation service so i can call navigation from my thunk action creators. Using a navigation service is discussed in this <a href="https://github.com/react-navigation/react-navigation/issues/1439">github ticket</a>. Use the NavigationContainerComponent type provided by react navigation when you are using a ref. My main app file uses it this way:</p><pre>&lt;AppNavigator<br>  ref={(navigatorRef: NavigationContainerComponent): void =&gt; {<br>    NavigationService.setTopLevelNavigator(navigatorRef);<br>  }}<br>/&gt;</pre><p>In your service file</p><pre>let _navigator: NavigationContainerComponent;</pre><pre>function setTopLevelNavigator(<br>  navigatorRef:NavigationContainerComponent<br>) {<br>     _navigator = navigatorRef;<br>  }</pre><pre>function navigate(routeName: string, params?: NavigationParams) {<br>  _navigator.dispatch(<br>    NavigationActions.navigate({<br>      routeName,<br>      params,<br>    })<br>  );<br>}</pre><p>TypeScript is a flexible utility, it allows you to be as precise or generic you want to be. ESLint does a fine job at making sure that we are keeping our code base neatly typed. On a couple of occasions i noticed that matching the typing between various libraries (react native and redux form) became a game of cat and mouse, as i poured through droves of .d.ts files only to find bugs or inconsistencies. Sometimes you end up using Function, Object and even Any as a type. For that I use the trusty // eslint-disable-next-line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d71b7360741" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/who-dares-wins-strictly-typed-react-native-with-redux-3d71b7360741">Who Dares Wins: Strictly Typed React Native With Redux</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native File Uploads with Axios And Redux Thunk]]></title>
            <link>https://medium.com/@istvanistvan/react-native-file-uploads-with-axios-and-redux-thunk-73d8093d7243?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d8093d7243</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Wed, 17 Jul 2019 00:52:12 GMT</pubDate>
            <atom:updated>2019-07-17T00:52:12.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOImM93eWhg-c4xJJWqmBA.png" /></figure><p>This is the second installment in my series on implementing image uploads with React Native. In my <a href="https://medium.com/@istvanistvan/react-native-custom-image-picker-with-upload-progress-5444e955455c">previous article,</a> we created a custom image picker and an upload progress component.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSJf8F4l0YUs%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSJf8F4l0YUs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSJf8F4l0YUs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f35a3ee21290a3d1e4f56683bfbf4f86/href">https://medium.com/media/f35a3ee21290a3d1e4f56683bfbf4f86/href</a></iframe><p>I now want to go over the upload service (thunk action creator) and how to communicate with our nodejs api using Axios. I’m using Redux for state management and Redux Thunk which is great for creating async services that allow you to dispatch multiple action creators, async or not. To clarify I’m calling the thunk methods services because technically action creators should return an object, so I will refer to thunks as services from now on. From within your view component, you can call your thunk upload service like so:</p><pre>function mapDispatchToProps(dispatch) {<br>    return {<br>        dispatchStorePhoto: photo =&gt; {<br>            dispatch(<br>                storePhoto(photo, {<br>                    userId: 1,<br>                })<br>            );<br>        },<br>    };<br>}</pre><p>So what does the thunk service look like? What will it do? Let’s create a file called S3.service.js. I have this file in a folder called s3 under modules. In this file create a function called storePhoto. This function takes two parameters, photo (CameraRoll photo object) and body (anything else you want to pass along to your API). This function will return a function, hence why its called a thunk. The returned function receives dispatch and getState. Now inside this function, you can use dispatch and also have access to redux state.</p><pre>export const storePhoto = (photo, body) =&gt; (dispatch, getState) =&gt; {<br>  const state = getState();<br>}</pre><p>It is from here where we want to call our API. First, let’s create a new file called s3.api.js. In this file, we’re going to import some libraries.</p><p><strong>Form Data</strong>: form-data is an npm package that allows you to create a FormData object key/value pairs representing form fields and their values, which can then be easily sent with XMLHttpRequest, in our case Axios.</p><p><strong>Axios:</strong> Promise based HTTP client for the browser and node.js</p><p>When you have these libraries imported we’ll create a class and a method inside of it. I called this method store, which to me is synonymous with save, and has nothing to do with our redux store.</p><p>We’ll need to pass a callback to this method, this is how we’ll hook into our progress bar component. Axios allows us to track upload progress by calling a function and from there we need to dispatch actions to the redux store. Since this class doesn’t have access to dispatch we’ll pass a callback from our thunk.</p><p>To create your form data, let’s create a function and pass in the stuff you want to send. See the gist below to see how our FormData is created.</p><p>When you’re creating your FormData it’s super important that when you send your file it contains a name and a uri. Without this, your upload won’t work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4142bcf4da2da12d40d888234d66ffda/href">https://medium.com/media/4142bcf4da2da12d40d888234d66ffda/href</a></iframe><p>Axios returns a promise so we’ll return this promise. If the upload fails we’ll throw an error in the catch statement, that we’ll later catch from our thunk method.</p><p>Let’s go back to our thunk. We’ll need to import our new S3.Api.js class and then call our store method. We can catch the thrown error here, for example let’s say our JWT is expired and we need to refresh the token.</p><pre>return S3Api.store(authToken, photo, body, progressCallback)<br>         .catch(error =&gt; {<br>           // If JWT token is expired, let&#39;s refresh it<br>           dispatch(handleTokenErrors(error.response.data));<br>         });</pre><p>We also need to create the progressCallback function. Axios will send the progress object as a parameter, we’ll call it progressEvent. The progress object has information about our file. We can create the percentage loaded using simple algebra.</p><pre>const progressCallback = progressEvent =&gt; { <br>  const percentFraction = progressEvent.loaded / progressEvent.total;<br>  const percent = Math.floor(percentFraction * 100); <br>}</pre><p>From this function, we need to save the percentage loaded in our redux Store. One thing that I’d like to note is that this callback is triggered every time there is an update, which could be hundreds of times. Since we’re building a native application, we don’t want to dispatch over and over again, it could freeze our application, so I decided to throttle the dispatches using a flag mechanism and dispatch when the percentage increments by 10 percent. You can also use debounce from lodash if you want. From the callback, we can update our redux store using dispatches with the file progress information, file size. When the promise returns from Axios the upload is finished! We can now reset our upload state and call it good.</p><p>This pretty much sums up this session. Take a look at the finished Thunk method below and feel free to leave a comment if you have any questions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8539869b149e00cd61e87e31d0fd227/href">https://medium.com/media/a8539869b149e00cd61e87e31d0fd227/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d8093d7243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Custom Image Picker With Upload Progress]]></title>
            <link>https://medium.com/@istvanistvan/react-native-custom-image-picker-with-upload-progress-5444e955455c?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/5444e955455c</guid>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 19:52:22 GMT</pubDate>
            <atom:updated>2019-07-12T23:47:10.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOImM93eWhg-c4xJJWqmBA.png" /></figure><p>Whether you’re building web or native applications, you’ll eventually be tasked with implementing a file uploader and in pursuit of the perfect solution. File uploads have a lot of moving parts. You have file pickers, progress bars, spinner icons, APIs that send progress back to the user with sockets or hooks, etc. Developers often resort to using pre-built components that are not very customizable. For example, React native gives us a pre-built image picker component. I wanted to modify it to use a dark theme but to my surprise, the background color cannot be changed. I decided to roll my own photo uploader from scratch because I wanted more control over the look and user experience. I wanted the upload to happen on a single screen, the design to be clean, the progress bar to show when the user initiates the upload and the gallery to animate out when the upload starts. Let me show you what I mean:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSJf8F4l0YUs%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSJf8F4l0YUs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSJf8F4l0YUs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b569d3985f1c4752feb256022a6747e6/href">https://medium.com/media/b569d3985f1c4752feb256022a6747e6/href</a></iframe><p>In this article, I’d like to show you how I did it, so without further ado let’s write some code.</p><p>I created a react component in my project called UploadScreen. This is where the 3 major components will live: The header, the progress bar, and the file picker. This is also where we fetch the photo data from the device gallery using the <a href="https://facebook.github.io/react-native/docs/cameraroll">CameraRoll</a> component and store it in component state.</p><pre>import { CameraRoll, TouchableOpacity, View } from &#39;react-native&#39;;</pre><pre>....</pre><pre>state = { photos: null, selectedPhoto: null };</pre><pre>componentDidMount() {<br>  const { navigation } = this.props;<br>   navigation.setParams({ upload: this.upload });<br>   this.getPhotosAsync({ first: 100 });<br>}</pre><pre>async getPhotosAsync(params) {<br>  return new Promise((res, rej) =&gt;<br>    CameraRoll.getPhotos(params)<br>      .then(data =&gt; {<br>        const assets = data.edges;<br>        const photos = assets.map(asset =&gt; asset.node.image);<br>           this.setState({ photos });<br>           res({ photos });<br>      })<br>      .catch(rej)<br>  );<br>}</pre><p>Once you have your data loaded into your component we need to create a new component. I called this CapaImagePicker and placed it in my components directory.</p><h3><strong>Image Picker Component</strong></h3><p>The image picker component takes the CameraRoll data as a prop and uses a horizontal FlatList to display the photos. Here is the FlatList that is in our render function.</p><pre>&lt;FlatList<br>  horizontal<br>  showsHorizontalScrollIndicator={false}<br>  renderItem={photo =&gt; {<br>    return this.renderPhoto(photo);<br>  }}<br>  keyExtractor={(photo, index) =&gt; index.toString()}<br>  data={photos}<br>/&gt;</pre><p>You will notice that the renderItem prop is a function that calls a method in our component called renderPhoto. This is where each photo will be rendered. When the user clicks the photo it will call the pickPhoto method which will then display the selected photo.</p><pre>renderPhoto = photo =&gt; {<br>  return (<br>    &lt;TouchableOpacity<br>      onPress={() =&gt; {<br>        this.pickPhoto(photo.item);<br>      }}<br>    &gt;<br>      &lt;Image source={{ uri: photo.item.uri }} style={styles.gallerImage} /&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br>};</pre><p>Here is the full gist of our component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3039fad927b685b98a05322e51bb1ce0/href">https://medium.com/media/3039fad927b685b98a05322e51bb1ce0/href</a></iframe><h3>Upload Progress Component</h3><p>The upload progress is a functional component. It receives the following props: uploadFilename, uploadFileSize, uploadProgress. These values come from Axios, and I’m storing them in redux state. Redux and Axios are beyond the scope of this article, I promise to write a follow up which will cover upload APIS and other related topics.</p><p>For the progress bar, I’m using a library called <a href="https://github.com/oblador/react-native-progress">react-native-progress</a>.</p><p>One thing I would like to point out is that the progress bar will only show the file upload progress. After the upload is complete the server will then process the image (upload it to S3) and that could be additional time, so I decided to use an animated icon to let the user know that the upload is being processed.</p><p>Below is the gist for this component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b16131eb441421f692ba85258880161/href">https://medium.com/media/1b16131eb441421f692ba85258880161/href</a></iframe><p>Now that we have both of our major components built out we need to have them talk to each other. We need our parent view to talk to the child components and the child components need to talk to the parent view. To be more specific I wanted to hide the FlatList gallery once the upload is initiated. In order to do this, we need to call a method in our ImagePicker from the parent view. One way to do this is by using refs. In the constructor of the UploadScreen let’s create a ref to the ImagePicker.</p><pre>constructor() {<br>   super();<br>   this.imagePicker = React.createRef();<br>}</pre><p>This allows us to call the toggleGallery() method inside our child ImagePicker component when the user initiates the upload. Also, we need the ImagePicker to set the state of the selectedPhoto. I’m using onChange prop to do this. See the gist below for our final UploadScreen component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d005366cacc8235d409224efb55b6eb/href">https://medium.com/media/1d005366cacc8235d409224efb55b6eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5444e955455c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Login Screen Style Strategy]]></title>
            <link>https://medium.com/@istvanistvan/react-native-login-screen-style-strategy-156ab37026ae?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/156ab37026ae</guid>
            <category><![CDATA[style-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Thu, 18 Apr 2019 13:56:05 GMT</pubDate>
            <atom:updated>2019-05-06T21:28:55.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmgW9syR3oEpehksain9uA.png" /></figure><p>In this article, I’m going to turn a login screen with no styles to a fully styled view, based on the inVision Studio mockup above. Using this approach, it&#39;s guaranteed to make your react native application more manageable, and your styles, reusable.</p><p>This is what we’re starting out with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrScwmHt1OmVQbHUwbBlkQ.png" /></figure><p>Below is a gist for the login screen. It imports the react-native-elements UI library and redux-form for the inputs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/994737e885d979b56b5904543f863082/href">https://medium.com/media/994737e885d979b56b5904543f863082/href</a></iframe><p><a href="https://react-native-training.github.io/react-native-elements/">React Native Elements</a> is a UI kit that lets developers build cohesive user interfaces. They have a wide variety of out of the box components that come handy when building mobile applications including Avatar, Badge, ButtonGroup, Card, etc. You can install it with</p><pre>npm install --save react-<strong>native</strong>-elements</pre><p>One cool thing about React Native Elements is that they allow theming of their components. We can start by identifying the components on the login screen. Just by looking at the view, it&#39;s easy to see that we’ll need to theme both input and button. Let’s begin by first changing the button component so it matches our design. We need to change the button background to black and the text to white. The text will be replaced by an icon but more on that later.</p><p>Go to your main app.js file and import ThemeProvider at the top of the file. Add your theme object and wrap your render code in the &lt;ThemeProvider&gt; tag</p><pre>import { ThemeProvider } from &#39;react-native-elements&#39;;</pre><pre>...</pre><pre>const theme = {<br>    Button: {<br>        buttonStyle: {<br>            backgroundColor: &#39;black&#39;,<br>        },<br>        titleStyle: {<br>            color: &#39;white&#39;,<br>        },<br>    },<br>};</pre><pre>...</pre><pre>return (<br>    &lt;ThemeProvider theme={theme}&gt;<br>        &lt;Provider store={store}&gt;<br>        &lt;View style={styles.container}&gt;<br>            {Platform.OS === &#39;ios&#39; &amp;&amp; &lt;StatusBar barStyle=&quot;default&quot; /&gt;}<br>            &lt;AppNavigator /&gt;<br>        &lt;/View&gt;<br>        &lt;/Provider&gt;<br>    &lt;/ThemeProvider&gt;<br>);</pre><p>This should give you a black login button with white text. Now let’s change the background. My application uses a black theme, and the view for each screen has a black background. We want to re-use this black background style in each view so I recommend creating a central place in our file structure within our expo app just for styles. I created a folder called styles at the root level. In the styles folder, I added index.js, colors.js, and theme.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rG5x6UrNntq3w1zpfK3FGg.png" /></figure><p>Let’s move the theme object from your app.js to the theme.js file. Export with default and then you can do an import in app.js</p><pre>import theme from &#39;./styles/theme&#39;;</pre><p>index.js will consolidate all of our styles that way you can import whatever you need for your components.</p><pre>import * as Colors from &#39;./colors&#39;;</pre><pre>export default { Colors };</pre><p>Add the following to color.js</p><pre>const background = {<br>    backgroundColor: &#39;black&#39;,<br>};</pre><pre>const whiteText = {<br>    color: &#39;white&#39;,<br>};</pre><pre>export { background, whiteText };</pre><p>Now that we have created our basic style structure, let’s go ahead and continue on the login screen. Import Colors from styles/index.js and the ImageBackground component which we need for the splash background image.</p><pre>import { StyleSheet, Text, View, ImageBackground } from &#39;react-native&#39;;<br>import { Colors } from &#39;../styles&#39;</pre><p>My current render function looks like this:</p><pre>&lt;View style={styles.container}&gt;<br>    &lt;View style={styles.header}&gt;<br>    &lt;/View&gt;<br>    &lt;View style={styles.body}&gt;<br>        &lt;ImageBackground  <br>            resizeMode=&quot;cover&quot; // or cover<br>            style={styles.body}<br>            source={require(&#39;../assets/images/signIn.jpg&#39;)}<br>        &gt;<br>            &lt;Text style={styles.text}&gt;Email&lt;/Text&gt;<br>            &lt;Field label=&quot;Email&quot; name=&quot;email&quot; component={renderEmail} /&gt;<br>            &lt;Text style={styles.text}&gt;Password&lt;/Text&gt;<br>            &lt;Field name=&quot;password&quot; component={renderPassword} /&gt;<br>            &lt;View&gt;<br>                &lt;Text&gt;{errorMessage}&lt;/Text&gt;<br>            &lt;/View&gt;<br>            &lt;View&gt;<br>                &lt;Button<br>                    style={styles.button}<br>                    testID=&quot;login&quot;<br>                    onPress={handleSubmit(submitForm)}<br>                    title=&quot;Login&quot;<br>                /&gt;<br>            &lt;/View&gt;<br>        &lt;/ImageBackground&gt;<br>    &lt;/View&gt;<br>&lt;/View&gt;</pre><p>I added the main View component with two subviews. The top subview will be the header, the bottom will be the body. Both of the subviews will have content aligned to the bottom using justifyContent: ‘flex-end’. The ImageBackground component holds the splash image. Inside ImageBackground I added another view called inputView which will hold our input fields and buttons. Let’s add padding to it using percentages in order to ensure it adapts to all screen sizes. In this case i added 10%.</p><p>Our styles block looks like this:</p><pre>const styles = StyleSheet.create({<br>    container: {<br>        ...Container.flexVerticalCenter,<br>        ...Colors.background,<br>    },<br>    header: {<br>        flex: 0.5,<br>        justifyContent: &#39;flex-end&#39;,<br>    },<br>    body: {<br>        ...Container.flexVerticalBottom,<br>        justifyContent: &#39;flex-end&#39;,<br>        paddingLeft: 0,<br>    },<br>    text: {<br>        fontSize: 11,<br>        ...Colors.whiteText,<br>    },<br>    input: {<br>        width: 150,<br>        borderBottomWidth: 0,<br>        marginBottom: 20,<br>    },<br>    squareButtonPos: {<br>        marginTop: &#39;-30%&#39;,<br>        marginLeft: &#39;75%&#39;,<br>    },<br>    inputView: {<br>        paddingHorizontal: &#39;10%&#39;,<br>        alignContent: &#39;flex-end&#39;,<br>    },</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf6zH6Q3s2x1TWio4Divhg.png" /></figure><p>Here is the current state of our styled login screen. Let’s continue with the header. I added the header and subheader text and used justifyContent: ‘flex-end’ to move the header text to the bottom of the header container.</p><pre>...<br>    header: {<br>        flex: 0.5,<br>        justifyContent: &#39;flex-end&#39;,<br>    },<br>    body: {<br>        ...Container.flexVerticalBottom,<br>        justifyContent: &#39;flex-end&#39;,<br>        paddingLeft: 0,<br>    },<br>    headerText: {<br>        fontSize: 54,<br>        marginLeft: 20,<br>        letterSpacing: 20,<br>        ...Colors.whiteText,<br>    },<br>    subheaderText: {<br>        marginBottom: 15,<br>        fontSize: 10,<br>        marginLeft: 20,<br>        ...Colors.whiteText,<br>    },</pre><pre>...</pre><pre>&lt;View style={styles.header}&gt;<br>    &lt;Text style={styles.headerText}&gt;CAPA&lt;/Text&gt;<br>    &lt;Text style={styles.subheaderText}&gt;#analog #nofilter #filmsnotdead&lt;/Text&gt;<br> &lt;/View&gt;</pre><p>I moved some of the input field styles to a new file called inputField.js in our styles directory.</p><pre>const inputText = {<br>    fontSize: 12,<br>};</pre><pre>const inputUnderline = {<br>    borderBottomWidth: 1,<br>    borderColor: &#39;white&#39;,<br>};</pre><pre>export { inputText, inputUnderline };</pre><p>We can use these in our Input component directly</p><pre>&lt;Input<br>    testID=&quot;password&quot;<br>    name=&quot;password&quot;<br>    inputContainerStyle={styles.input}<br>    inputStyle={[Colors.whiteText, InputField.inputText]}<br>    onChangeText={onChange}<br>    secureTextEntry<br>    {...restInput}<br>/&gt;</pre><p>Moving onto the login button. In order to add the play arrow icon we have to import an icon set. Expo has its own icon set, to install it, add it to your project using npm:</p><pre>npm install @expo/vector-icons</pre><p>Then import it in your view</p><pre>import { Ionicons } from &#39;<a href="http://twitter.com/expo/vector-icons">@expo/vector-icons</a>&#39;;</pre><p>Modify the button component like so:</p><pre>&lt;Button<br>  icon={<br>    &lt;Ionicons name=&quot;md-arrow-dropright&quot; size={26} color=&quot;white&quot; /&gt;<br>  }<br>  style={styles.button}<br>  buttonStyle={styles.squareButton}<br>  testID=&quot;login&quot;<br>  onPress={handleSubmit(submitForm)}<br>/&gt;</pre><p>I also added a “new account” button that&#39;s clear to the bottom of the screen.</p><pre>&lt;Button<br>    type=&quot;clear&quot;<br>    buttonStyle={[styles.clearButton, styles.newaccount]}<br>    testID=&quot;newaccount&quot;<br>    title=&quot;NEW ACCOUNT&quot;<br>/&gt;</pre><p>In order to override the black button theme add type=”clear” to the button props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aoiw-QnXLHD1WMTVUUNwBw.png" /></figure><p>As you can see from the screenshot above I created 2 input components EmailFeild and PasswordField. These components use the redux-form style input fields. Each component includes a label as well. I created a directory under my components folder called fields. I placed my field components here so anytime I need an email or password field they’re reusable components.</p><p>Here is the code for the emailField.js component inside the fields folder.</p><pre>import React from &#39;react&#39;;<br>import { Input } from &#39;react-native-elements&#39;;<br>import { Field } from &#39;redux-form&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { Colors, InputField } from &#39;../../styles&#39;;</pre><pre>const renderEmail = ({ input: { onChange }, ...restInput }) =&gt; {<br>    return (<br>        &lt;Input<br>            testID=&quot;email&quot;<br>            placeholderTextColor=&quot;white&quot;<br>            inputStyle={[Colors.whiteText, InputField.inputText]}<br>            onChangeText={onChange}<br>            {...restInput}<br>        /&gt;<br>    );<br>};</pre><pre>renderEmail.propTypes = {<br>    input: PropTypes.shape({}).isRequired,<br>};</pre><pre>export default function emailField(props) {<br>    const { inputContainerStyle, placeholder } = props;</pre><pre>return (<br>        &lt;Field<br>            inputContainerStyle={inputContainerStyle}<br>            label=&quot;EMAIL&quot;<br>            placeholder={placeholder}<br>            labelStyle={InputField.inputLabel}<br>            name=&quot;email&quot;<br>            component={renderEmail}<br>        /&gt;<br>    );<br>}</pre><pre>emailField.propTypes = {<br>    inputContainerStyle: PropTypes.shape({}).isRequired,<br>    placeholder: PropTypes.string,<br>};</pre><pre>emailField.defaultProps = {<br>    placeholder: &#39;&#39;,<br>};</pre><p>Here is the finished login screen next to the inVision Studio mock-up. On the left is the original design, in the middle iPhone X, and on the right is the small viewport Iphone SE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxaVEhxN2-4Ugj4eT2DfFQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156ab37026ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing nodejs CRUD APIs in 2019 (Part 2)]]></title>
            <link>https://medium.com/@istvanistvan/unit-testing-nodejs-crud-apis-in-2019-part-2-5e2c9907ccdc?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2c9907ccdc</guid>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[supertest]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 16:54:29 GMT</pubDate>
            <atom:updated>2020-06-05T21:05:54.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*lbWwl0LiqSyFPwbVi39q8g.jpeg" /></figure><p>In <a href="https://medium.com/@istvanistvan/unit-testing-nodejs-crud-apis-in-2019-part-1-9c4feadb4818">part one</a> of this article, I went over some basics of unit testing and why I chose Mocha as a testing framework. In part 2 let’s get started with setting up our testing environment.</p><p>Install Mocha, Chai, Supertest</p><pre>npm install mocha --save<br>npm install chai --save<br>npm install supertest --save</pre><p>Configure your package.json file so that the npm test command works:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;./node_modules/.bin/mocha&quot;,<br>  &quot;start&quot;: &quot;node index.js&quot;,<br>  &quot;server&quot;: &quot;nodemon index.js&quot;,<br>  &quot;db&quot;: &quot;mongod --dbpath /usr/local/var/mongodb/ --rest&quot;<br>},</pre><p>When you install mocha locally, npm adds a mocha executable inside node_modules/.bin/</p><p>Now create a directory called ‘test’ in your document root and then create a file called hellotest.js inside that folder</p><pre>mkdir test<br>vi test/hellotest.js</pre><p>Let’s write a simple test case:</p><pre>var assert = require(&#39;assert&#39;);<br>describe(&#39;Basic Mocha String Test&#39;, function () {<br>  it(&#39;should return number of characters is 5&#39;, function () {<br>    assert.equal(&quot;Hello&quot;.length, 5);<br>  });<br>});</pre><p>save it and then run npm test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yFhhk06yuWT6O51PIHANA.png" /></figure><p>You should see your first test passing.</p><p>In order to get supertest working we need to modify our server file and make sure that we export our app with</p><pre>module.exports = app;</pre><p>next, let’s create another test file in our test directory called login.js</p><pre>var app = require(&#39;../index.js&#39;),<br>  chai = require(&#39;chai&#39;),<br>  request = require(&#39;supertest&#39;);</pre><pre>describe(&#39;POST /login&#39;, function() {<br>  it(&#39;responds with json&#39;, function(done) {<br>  request(app)<br>    .post(&#39;/api/auth/login&#39;)<br>    .send({email: &#39;user@email.com&#39;, password: &#39;yourpassword&#39;}<br>    .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>    .expect(&#39;Content-Type&#39;, /json/)<br>    .expect(200)<br>    .end(function(err, res) {<br>      if (err) return done(err);<br>      done();<br>    });<br>  });<br>});</pre><p>At the top of this file we include our server, chai and supertest. This test makes sure that the login route returns status 200 with content type json. Make sure your server is shut off and run our tests.</p><pre>npm test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcrQdIG30EGUyTTrMquLgA.png" /></figure><p>You might notice that this test doesn’t actually care whether or not the email/password works. How can we change our code to test the email/password ?</p><p>Let’s take a look at what the API returns on a successful login inside postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5J-4gImhSIjkz-bdONy9Kg.png" /></figure><p>We need to check to make sure that success is returned as true. In order to do that we can try the following. Note that I added the should library so we can write res.body.success.should.equal(true);</p><pre>var app = require(&#39;../index.js&#39;),<br>assert = require(&#39;assert&#39;),<br>chai = require(&#39;chai&#39;),<br>should = require(&#39;should&#39;);<br>request = require(&#39;supertest&#39;);</pre><pre>describe(&#39;POST /login&#39;, function() {<br>  it(&#39;logs user in&#39;, function(done) {<br>    request(app)<br>    .post(&#39;/api/auth/login&#39;)<br>    .send({email: &#39;your@email.com&#39;, password: &#39;yourpassword&#39;})<br>    .set(&#39;Accept&#39;, &#39;application/json&#39;)<br>    .expect(&#39;Content-Type&#39;, /json/)<br>    .expect(200).end(function(err,res){<br>      res.status.should.equal(200);<br>      res.body.success.should.equal(true);<br>      done();<br>    });<br>  });<br>});</pre><p>If we run this test, we can now check for a successful authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRv4TNKjONM0FuEUDM3X_w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2c9907ccdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing nodejs CRUD APIs in 2019 (Part 1)]]></title>
            <link>https://medium.com/@istvanistvan/unit-testing-nodejs-crud-apis-in-2019-part-1-9c4feadb4818?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c4feadb4818</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mocha]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 13:21:00 GMT</pubDate>
            <atom:updated>2019-04-15T18:12:24.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yQqYn89rTVXUTr02dwX8OA.gif" /></figure><p>In my <a href="https://medium.com/@istvanistvan/testing-react-native-applications-using-detox-48d08cb4c090">previous article</a>, we covered unit testing front end react native applications using Detox. I would like to continue on the subject of unit testing but for server side applications. In this article, I’m going to look into unit testing strategies for a nodejs CRUD API that is built on express and mongodb. My API currently has JWT authentication implemented along with a photo upload route that uploads an image to Amazon AWS.</p><p><strong>The state of server-side js unit tests in 2019</strong></p><p>Let’s look at some of the options available to us for testing node applications. A quick google search on node testing leads us lots of different testing strategies and frameworks. Mocha, Chai, and Sinon to name a few. But before we can talk about them, let us familiarize ourselves with some of the terminologies that you might encounter when it comes to the topic of software testing.</p><p>Test Runner — A test runner is a software library or tool that targets a directory in your source code and executes the test scripts located within. This process usually happens in the console.</p><p>Testing Framework — In order to write testing scripts that the test runner can pick up and execute we need to actually write some code. You’ll be using a testing framework to write these scripts. It is the testing framework that can understand the code that we write, it handles setup, teardown, and structure.</p><p>Assertion Library —In order to test software we have to write assertions. Assertions are boolean expressions that will either be true or false. When our assertions are valid, the test can be marked as passed. If there is a bug in our software our assertions will fail. Some frameworks will come with their own assertion library, like Jasmine.</p><p>Code coverage — Code coverage is a measurement based on the number of lines that your automated tests cover. It is usually a report that shows you the percentage of code executed.</p><p>So now that we have that out of the way let’s pick a testing strategy. We need a test runner, a testing framework and an assertion library to start out with. Since we’re testing a crud api, it would make sense to pick a terminal based testing framework. Our first immediate candidate is <a href="https://mochajs.org/">Mocha</a>. It is by far the most popular node testing test runner/framework bundle. Its always a good idea to look at the github repository to make sure its actively being maintained. But just to make sure let’s look at some alternatives to Mocha. I found this link that gives us a nice list of candidates.</p><p><a href="https://www.slant.co/options/12696/alternatives/~mocha-alternatives">Slant - 16 best alternatives to Mocha as of 2019</a></p><p>After looking at this list, Based on our criteria, Jasmine seems like a good candidate; it includes its own assertion library, while Mocha doesn’t. Jasmine also includes spies, which are test double functions. Which one will we choose?</p><h4>Enter SuperTest</h4><p>Supertest is a library that was created just for testing APIs. It is well documented and it is commonly used with Mocha and Chai. It makes API testing super concise. I think it is a good fit for our project, so this is the reason why I’m choosing to go with Mocha and Chai. Without further ado, let&#39;s begin installing our testing environment.</p><p>To be continued in Part 2…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c4feadb4818" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Native applications using Detox]]></title>
            <link>https://medium.com/@istvanistvan/testing-react-native-applications-using-detox-48d08cb4c090?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/48d08cb4c090</guid>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[detox]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Tue, 09 Apr 2019 17:35:54 GMT</pubDate>
            <atom:updated>2019-04-09T18:57:39.023Z</atom:updated>
            <content:encoded><![CDATA[<p>If you practice Test Driven Development, or you want fully automated functional tests, Snapshot testing with Jest is insufficient. Let’s say you want to E2E test a login screen. Test Driven Development always begins with writing tests first followed by implementation of the functionality. So how would one go about writing an end to end test for a login screen? You have to imagine what a use case might be for the end user. We want to describe the login flow with simple key phrases. So for a login screen, the user will most likely see two inputs and a button to log in. When the user taps the login button they should be able to log in. Simple enough. Using these key phrases we can now construct a test case. With Detox it looks like this</p><pre>const { reloadApp } = require(&#39;detox-expo-helpers&#39;);</pre><pre>describe(&#39;Login flow&#39;, () =&gt; {<br>  it(&#39;should login successfully&#39;, async () =&gt; {<br>    await reloadApp();<br>    await expect(element(by.id(&#39;email&#39;))).toBeVisible();<br>    await element(by.id(&#39;email&#39;)).replaceText(&#39;hello<a href="/service/mailto:istvanskeri@gmail.com">@email.com</a>&#39;);<br>    await element(by.id(&#39;password&#39;)).replaceText(&#39;foobar&#39;);<br>    await element(by.id(&#39;login&#39;)).tap();<br>    await expect(element(by.text(&#39;Welcome&#39;))).toBeVisible();<br>    await expect(element(by.id(&#39;email&#39;))).toNotExist();<br>  });<br>});</pre><p>So what is Detox? <a href="https://github.com/wix/Detox">Detox</a> is a project created by Wix. It runs on devices / Simulators, it is described as a grey box testing environment (as opposed to black box where we have no knowledge of the internal structure of the system), and it works with any test runner.</p><p>My react native project uses Expo and Jest. To install Detox with expo follow the instructions on the detox’s <a href="https://github.com/wix/Detox/blob/master/docs/Guide.Expo.md">github page</a>. Once you have everything set up you can create your first test in the e2e folder. First make sure you have expo running. You can initiate the test using the ‘detox test’ command. Detox will first open the Expo Client app and then start your project and run the tests.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKQvM9LdIKBU%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKQvM9LdIKBU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKQvM9LdIKBU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a92423bf1258507cbbee606d91ebb49a/href">https://medium.com/media/a92423bf1258507cbbee606d91ebb49a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48d08cb4c090" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why use Redux Thunk?]]></title>
            <link>https://medium.com/@istvanistvan/why-use-redux-thunk-1ca326d6a46?source=rss-3ba5eb362060------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca326d6a46</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[thunk]]></category>
            <dc:creator><![CDATA[Istvan Keri]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 19:42:20 GMT</pubDate>
            <atom:updated>2019-04-09T18:08:31.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Redux Thunk is a popular middleware for React Redux. You can create services that return a function hence the name Thunk. The creators of Thunk call this function ‘action creators’. Here is a quote from GitHub:</p><p>“Redux Thunk <a href="https://github.com/reactjs/redux/blob/master/docs/advanced/Middleware.md">middleware</a> allows you to write action creators that return a function instead of an action.”</p><p>For me personally, it makes more sense to think of these thunk functions as services since they don’t return actions. Remember that actions are plain objects. Your thunk function will call dispatch, so you’ll be calling dispatch at least twice. Once from your component when you call your service. And then again inside of your thunk function to trigger your reducer.</p><p>Redux Thunk looks for these special functions and handles the dispatching for you. This pattern allows you to centralize and re-use these services in different components. This especially comes handy when you are making asynchronous API requests and you need to dispatch on promise success and error.</p><p>A common misconception is that with Redux you can’t dispatch actions from within async calls. In fact, It’s technically possible, just not recommended.</p><p>For a detailed discussion:</p><p><a href="https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux/34599594#34599594">Why do we need middleware for async flow in Redux?</a></p><p>Here is an example of a login service that uses Thunk.</p><pre>export const login = (email, password) =&gt; dispatch =&gt; {    <br>  dispatch(AuthReducer.setAuthPending());<br>  return AuthApi.login(email, password)<br>    .then(response =&gt; {<br>      if (response.success) {<br>        dispatch(<br>          AuthReducer.setLoginSuccess(response.authToken,  response.refreshToken)<br>        );<br>        _saveItem(‘authToken’, response.authToken)<br>        .then(resp =&gt; {<br>          _saveItem(‘refreshToken’, response.refreshToken)<br>          .then(resp =&gt; {<br>            App.startAppLoggedIn();<br>          })<br>          .catch(error =&gt; {<br>            dispatch(asyncError(error));<br>          });<br>        })<br>        .catch(error =&gt; {<br>          dispatch(asyncError(error));<br>        });<br>      } else {<br>        dispatch(AuthReducer.setLoginError(response.message));<br>      }<br>   })<br>   .catch(error =&gt; {<br>     dispatch(generalError(error));<br>   });<br>};</pre><p>In conclusion, Redux Thunk uses a pattern that promotes abstracting store logic out of components and into services, action creators, and actions. Your components shouldn’t care about what happens to the data store, all you need to do is dispatch the login service. You want to use Thunk so you can do this:</p><pre>function mapDispatchToProps(dispatch) {<br> return {<br>  login: (email, password) =&gt; {<br>   dispatch(login(email, password));<br>  }<br> };<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca326d6a46" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>