How to safely access deeply nested object in Javascript

Issue #390 An object ’s property can be null or undefined. Accessing step by step is tedious props.user && props.user.posts && props.user.posts[0] && props.user.posts[0].comments Dynamic parsing path is too clever and involves string in the end, which is a no no const get = (p, o) => p.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, o) const getUserComments = get(['user', 'posts', 0, 'comments']) Instead let’s use function and catch errors explicitly, and defaults with a fallback...

September 3, 2019 · 1 min · Khoa Pham

How to use flow type in Javascript

Issue #389 Prefer flow over TypeScript for simplicity Javascript primitive types number and string are too general and do not express the domain objects. Because lack of type alias in Javascript, we can use flow export type Centimeter = number export type Color = string export type ImageSource = number export type Kilogram = number export type Kilocalorie = number // 1 cal = 4.1840 J export type Second = number export type SecondsSince1970 = number export type Minute = number export type DateString = string // 2018-11-20 export type DateTimeString = string // 2018-11-20T00:00:00 export type YearWeekString = string // 201838 export type FunctionWithVoid = () => void export type FunctionWithString = (string) => void export type FunctionWithBoolean = (boolean) => void export type FunctionWithNumber = (number) => void export type JSONObject = any export type JSONString = string export type StringToString = any export type Degree = number export type Radian = number export type Animal = 'cat' | 'dog' | 'cow'

September 3, 2019 · 1 min · Khoa Pham

How to use React JSX with Babel in Electron

Issue #352 For a normal electron app created with npm init, we can use all features of ES6, but not the JSX syntax for React. We can use just Babel to transpile JSX, as used in IconGenerator .babelrc { "plugins": [ "transform-react-jsx-source" ], "presets": ["env", "react"] } And in package.json, call babel to transpile src to dist "main": "dist/main.js", "scripts": { "start": "npm run babel && electron .", "babel": "babel ....

August 12, 2019 · 1 min · Khoa Pham

How to submit electron app to AppStore

Issue #342 Before Install electron as dev npm install electron --save-dev Update electron-packager npm install electron-packager@latest --save-dev Use no space in app name Package with electron-packager Follow https://github.com/electron/electron-osx-sign/wiki/Packaging-and-Submitting-an-Electron-App-to-the-Mac-App-Store npx electron-packager . "MyApp" --app-bundle-id=com.onmyway133.MyApp --helper-bundle-id=com.onmyway133.MyApp.helper --app-version=1.4.0 --build-version=1.0.100 --platform=mas --arch=x64 --icon=Icon/Icon.icns --overwrite npx electron-osx-sign "MyApp-mas-x64/MyApp.app" --verbose npx electron-osx-flat "MyApp-mas-x64/MyApp.app" --verbose If you have multiple developer identities in your keychain: electron-osx-sign searches your keychain for the first signing certificates that it can locate....

July 31, 2019 · 2 min · Khoa Pham

How to organise test files

Issue #327 In terms of tests, we usually have files for unit test, UI test, integeration test and mock. Out of sight, out of mind. Unit tests are for checking specific functions and classes, it’s more convenient to browse them side by side with source file. For example in Javascript, Kotlin and Swift index.js index.test.js index.mock.js LocationManager.kt LocationManager.mock.kt LocationManager.test.kt BasketHandler.swift BasketHandler.mock.swift BasketHandler.test.swift Integration tests check features or sub features, and may cover many source files, it’s better to place them in feature folders...

June 25, 2019 · 1 min · Khoa Pham

What is create-react-native-app

Issue #279 Original post https://medium.com/fantageek/what-is-create-react-native-app-9f3bc5a6c2a3 As someone who comes to React Native from iOS and Android background, I like React and Javascript as much as I like Swift and Kotlin. React Native is a cool concept, but things that sound good in theory may not work well in practice. Another layer of abstraction Up until now, I still don’t get why big companies choose React Native over native ones, as in the end what we do is to deliver good experience to the end user, not the easy development for developers....

May 23, 2019 · 5 min · Khoa Pham

How to make tag selection view in React Native

Issue #271 Original post https://hackernoon.com/how-to-make-tag-selection-view-in-react-native-b6f8b0adc891 Besides React style programming, Yoga is another cool feature of React Native. It is a cross-platform layout engine which implements Flexbox so we use the same layout code for both platforms. As someone who uses Auto Layout in iOS and Constraint Layout in Android, I find Flexbox bit hard to use at first, but there are many tasks that Flexbox does very well, they are distribute elements in space and flow layout....

May 23, 2019 · 6 min · Khoa Pham

Getting to know some pragmatic programming language features

Issue #270 As you know, in the Pragmatic Programmer, section Your Knowledge Portfolio, it is said that Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getting stuck in a rut. Additionally, learning many languages is far easier now, thanks to the wealth of freely available software on the Internet...

May 23, 2019 · 8 min · Khoa Pham

How to add app icons and splash screens to a React Native app in staging and production

Issue #268 React Native was designed to be “learn once, write anywhere,” and it is usually used to build cross platform apps for iOS and Android. And for each app that we build, there are times we need to reuse the same code, build and tweak it a bit to make it work for different environments. For example, we might need multiple skins, themes, a free and paid version, or more often different staging and production environments....

May 23, 2019 · 12 min · Khoa Pham

Get to know different JavaScript environments in React Native

Issue #266 Original post https://medium.freecodecamp.org/get-to-know-different-javascript-environments-in-react-native-4951c15d61f5 React Native can be very easy to get started with, and then at some point problems occur and we need to dive deep into it. The other day we had a strange bug that was only occurring in production build, and in iOS only. A long backtrace in the app revealed that it was due to Date constructor failure. const date = new Date("2019-01-18 12:00:00") This returns the correct Date object in debug mode, but yields Invalid Date in release....

May 23, 2019 · 5 min · Khoa Pham

How to Make Linear Gradient View with Bridging in React Native

Issue #264 Original post https://medium.com/react-native-training/react-native-bridging-how-to-make-linear-gradient-view-83c3805373b7 React Native lets us build mobile apps using only Javascript. It works by providing a common interface that talks to native iOS and Android components. There are enough essentials components to get started, but the cooler thing is that it is easy to build our own, hence we are not limited by React Native. In this post we will implement a linear gradient view, which is not supported by default in React Native, using native UI component, particularly CAGradientLayer in iOS and GradientDrawable in Android....

May 23, 2019 · 11 min · Khoa Pham

How to dismiss keyboard with react-navigation in React Native apps

Issue #263 Original post https://medium.com/react-native-training/how-to-dismiss-keyboard-with-react-navigation-in-react-native-apps-4b987bbfdc48 Showing and dismiss keyboard seems like a trivial thing to do in mobile apps, but it can be tricky in automatically dismissing it when it comes together with react-navigation and modal presentation. At least that’s according to my initial assumption. This article aims to detail what I have learned about keyboard handling and how to avoid extra tap when dealing with TextInput There will also be lots of code spelunking, thanks to the all the libraries being open source....

May 23, 2019 · 8 min · Khoa Pham

How to structure your project and manage static resources in React Native

Issue #256 Original post https://medium.freecodecamp.org/how-to-structure-your-project-and-manage-static-resources-in-react-native-6f4cfc947d92 React and React Native are just frameworks, and they do not dictate how we should structure our projects. It all depends on your personal taste and the project you’re working on. In this post, we will go through how to structure a project and how to manage local assets. This of course is not written in stone, and you are free to apply only the pieces that suit you....

May 23, 2019 · 14 min · Khoa Pham

How to overlay view on another view in React Native

Issue #254 Original post https://stackoverflow.com/a/54108708/1418457 Make our own convenient OverlayContainer. The trick is to use absolute with 100% size // @flow import React from 'react' import { View, StyleSheet } from 'react-native' type Props = { behind: React.Component, front: React.Component, under: React.Component } // Show something on top of other export default class OverlayContainer extends React.Component<Props> { render() { const { behind, front, under } = this.props return ( <View style={styles....

May 22, 2019 · 1 min · Khoa Pham

How to remove Cartography in iOS

Issue #252 Read more https://medium.com/flawless-app-stories/how-to-make-auto-layout-more-convenient-in-ios-df3b42fed37f Description This is a script to remove Cartography, and use plain NSLayoutAnchor syntax. Use Constraint.on() from Sugar. It will change all .swift files recursively under provided folder. Constraint.on( logoImageView.widthAnchor.constraint(equalToConstant: 74), view1.leftAnchor.constraint(equalTo: view2.leftAnchor, constant: 20), ) Features Parse recursively Parse a single file Parse each constrain block separately Handle ==, >=, <= Handle center, edges Infer indentation Handle relation with other item Handle relation with constant Handle multiplier Auto import Sugar Infer superView Prepare Install tool if needed...

May 21, 2019 · 5 min · Khoa Pham

How to sort strings with number in Javascript

Issue #251 function sort() { const string = ` - Favorite WWDC 2017 sessions https://github.com/onmyway133/blog/issues/56 - Favorite WWDC 2018 sessions https://github.com/onmyway133/blog/issues/245 - How to do clustering with Google Maps in iOS https://github.com/onmyway133/blog/issues/191 ` const lines = string .split('\n') .filter((line) => { return line.length > 0 }) .map((line) => { let parts = line.trimEnd().split(' ') let lastPart = parts[parts.length-1] let number = lastPart.replace('https://github.com/onmyway133/blog/issues/', '') return { line, number: parseInt(number) } }) lines....

May 21, 2019 · 1 min · Khoa Pham

How to catch error in ApolloClient

Issue #192 Read https://www.apollographql.com/docs/react/features/error-handling How to catch actual error https://github.com/apollographql/apollo-client/issues/4016 🤔 import { Observable } from 'apollo-link' import ApolloClient from 'apollo-boost' import Token from 'library/models/Token' import TokenService from './TokenService' import { TokenRefreshException } from 'library/utils/Exception' const client = new ApolloClient({ uri: 'https://www.myapp.no/api/', request: async (operation) => { const token = await TokenService.loadToken() updateOperation(operation, token) }, onError: (error) => { console.log('ApolloClient error', error) if (isAuthError(error)) { return handleAuthError(error) } else { return error....

March 28, 2019 · 1 min · Khoa Pham

Curry in Swift and Javascript

Issue #185 You may encounter curry in everyday code without knowing it. Here is a bit of my reflections on curry and how to apply it in Javascript and Swift. Taking one parameter in Haskell In Haskell, all function officially takes only 1 parameter. Function with many parameters are just curried, which means they will be partially applied. Calling sum 1 just returns a function with 1 parameter, then 2is passed into this function....

March 24, 2019 · 6 min · Khoa Pham

How to get properties of JSValue in JavascriptCore

Issue #179 let rough = context.objectForKeyedSubscript("myObject") myObject.toDictionary()

March 19, 2019 · 1 min · Khoa Pham

Learning flexbox

Issue #62 CSS body height https://www.kirupa.com/html5/make_body_take_up_full_browser_height.htm Flexbox Properties of flex https://codepen.io/enxaneta/full/adLPwv Visual guide to flexbox https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties align-items vs align-content https://stackoverflow.com/questions/27539262/whats-the-difference-between-align-content-and-align-items align-items vs justify-content https://stackoverflow.com/questions/35049262/difference-between-justify-content-vs-align-items multiple line https://stackoverflow.com/questions/41789278/first-child-full-width-in-flexbox

August 4, 2017 · 1 min · Khoa Pham