How to autoFocus a TextInput field within a Modal in React-Native

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Using the autoFocus prop with TextInputs in React-Native is normally straightforward. However, I’ve noticed that attempting to autoFocus TextInput fields contained within the simple <Modal/> component that comes with React-Native, or the 3rd party react-native-modal doesn’t seem to work. I think the problem likely has to do with how the <Modal/> component is designed. You typically embed the <Modal/> on a screen and just toggle the value of a prop whenever you want to show or hide it. And for whatever reason, this doesn’t seem to play well with autoFocus.

But fret not! Over on Stack Overflow I discovered an excellent work-around from Saleel. Saleel suggests that instead of using autoFocus, give your TextInput a ref, and then use that ref from within the Modal’s onShow method to call the TextInput’s .focus() method:

<Modal
visible={true}
onShow={ () => { this.textInput.focus(); }}>
{/* Adapted From: https://stackoverflow.com/questions/42730400/focus-input-on-load-of-modal-in-react-native */}
<KeyboardAvoidingView style={{}}>
<TextInput
style={{}}
ref={ (input) => { this.textInput = input; }}
placeholder=" Enter Text Here"
onChangeText={ (text) => console.log(text) }
value={ null } />
<Button
title="Submit"
onPress={ () => console.log("do stuff...") } />
</KeyboardAvoidingView>
</Modal>
 

How to skip, filter, and remove items and rows when rendering a FlatList in React Native

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Having trouble working with FlatList’s in React Native? Something I have been struggling to figure out recently is how to go about excluding certain items and rows when rendering a FlatList in React Native. For example, let’s say you have an array of items stored in either Redux or in React’s built-in component state and you want to remove the item? Well this is fairly straight forward, you just remove the item from the store and the FlatList will update accordingly. However, what if you want to keep the item in the store but you want to filter it out from your FlatList?

Unfortunately the React Native docs don’t mention how to do this exactly. Furthermore, I wasn’t able to find any blog posts or Stack Overflow answers regarding this either. However, I was able to stumble upon the answer today while experimenting, so here is the answer:

If you wish to skip, filter, remove, or omit an item from your FlatList, add some conditional logic to your <FlatListItem /> component’s render method so that it returns nothing <></> when passed a particular prop. For example, take a look at my GitHub gist below. In the example I have a list of three items stored in my my <App/>’s component state. The three items are called “foo”, “bar”, and “baz”. Now, in the <FlatListItem />’s render method I have added some logic which states if the item is equal to “bar”, render nothing <></>.

import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
FlatList,
} from 'react-native';
// SEE BLOG POST FOR EXPLANATION REGARDING HOW TO SKIP
// OVER CERTAIN ITEMS AND ROWS IN A REACT NATIVE FLAT LIST
// https://topherpedersen.blog/2020/05/16/how-to-skip-filter-and-remove-items-and-rows-when-rendering-a-flatlist-in-react-native/
class FlatListItem extends React.Component {
constructor(props) {
super(props);
}
render() {
if (this.props.text !== "bar") {
return(
<View>
<Text>{this.props.text}</Text>
</View>
);
} else {
return(
<></>
);
}
}
}
const Empty = <></>;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{text: "foo"},
{text: "bar"},
{text: "baz"},
],
}
}
render() {
return(
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 15}}>
<Text style={{textAlign: 'center'}}>FlatListApp</Text>
</View>
<View style={{flex: 85, justifyContent: 'center', backgroundColor: 'white'}}>
<FlatList
key="flat-list-key"
data={this.state.items}
renderItem={({ item }) => (
<FlatListItem text={item.text} />
)}
keyExtractor={ (item, index) => index.toString() }/>
</View>
</SafeAreaView>
);
}
}
export default App;

So that’s all there is to it! Break the items you wish to render off into their own class components, and then add some logic to render nothing <></> under some particular condition, and React Native will simply skip over that item when rendering the FlatList.

 

Who is Delane Parnell? and how did he convince investors to give him $96,000,000?

Yesterday, the This Week in Startups podcast featured an interesting guest with a fantastic tale: Delane Parnell, CEO and founder of PlayVS— the “Official High School eSports League.” The thing that stuck out for me watching the episode was the guest’s seemingly unbelievable story. Parnell paints an origin story of himself as a sort of business prodigy who from a young age was always destined for great success. He claims to have kicked off his entrepreneurial career by opening his own cell phone store in Detroit at age 16 while still in High School, before moving on to start his own car rental business around the same time.

After selling his stores and car rental business, Parnell became a figure in the Detroit startup scene by launching his own startup event and speaker series modeled after Jason Calacanis’s Launch Festival. Leveraging his newly found status in the Detroit entrepreneur scene, Parnell landed a job at a small seed stage Venture Capital firm becoming the youngest black Venture Capitalist in America.

All of this leads to Parnell meeting LA based startup founder and venture capitalist Peter Pham at SXSW in 2017 who convinced him to “move to LA to become a billionaire.” Enticed by Pham, Parnell moves to Los Angeles and goes on to raise nearly $100,000,000 for his newly founded startup, PlayVS, in just 13 months!

But it makes you wonder: How did a young man with little experience in eSports, no computer programming skills, and no experience creating tech startups, convince investors to give him $96,000,000? Had Parnell raised $96,000 the story above might make some sense. But $96,000,000?

From my research PlayVS’s footprint and web presence does not match the amount of funding they have raised. They have a very small following on Twitch, around 1,000 followers. And after registering as a player (and coach) on their website, I discovered that their website is empty and unfinished. From what I could tell, they are currently using a lean startup style website that appears at first glance to be fully functioning, but is really just a tool for collecting email addresses. According to Parnell there is currently a wait-list to join, so that maybe explains a few things. But from my research it certainly looks a lot like vaporware to me. For example, here’s what the website looks like if you signup as a player:

The site simply notifies the player that his school needs a coach. Sounds reasonable right? But after registering a coach account with a different email address, the website is empty for coaches as well:

There’s nothing there! You can click on the user icon to update the coaches personal information, but that’s it! So when Parnell says that there is currently a “waitlist,” it’s quite possible that PlayVS hasn’t actually built anything yet and is using the term “waitlist” as a convenient euphemism.

I don’t know. I may be wrong, but what do you think? Could Delane Parnell be the next Evan Spiegal? Or is he the next Billy McFarland? Only time will tell, so we’ll have to see how this post ages. But if PlayVS does happen to fail spectacularly, you heard it here first!

Note, at the time of this blog post https://topherpedersen.blog has a higher Alexa Internet Ranking in the United States than https://playvs.com. Red flag?

 

Simple String Similarity Algorithm in JavaScript or, How to Tell if Two Strings are Similar, even if they aren’t exactly the same

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

At the moment I happen to be working on a personal finance app called BitBudget, where I need to be able to figure out if two purchases were made with the same merchant, or different merchants. For example, does a financial transaction labeled “VZWRLSS*PRPAY AUTOPAY 02/19 PURCHASE” represent a transaction with the same company as “VZWRLSS*PRPAY AUTOPAY 03/19 PURCHASE”? What about “CALM 03/26 PURCHASE” and “CALM 02/26 PURCHASE INTERNET”? Many transactions are easy to compare, “McDonald’s” vs “Amazon”, or “Chipotle Mexican Grill” vs “Starbucks”, but once banks and payment processors start throwing in all this extra information things get tricky.

While I personally am not really a computer science / algorithms kind of guy, sometimes you really need an algorithm to get the job done! So if you find yourself in the same boat I have your answer right here. After a quick google search on this topic I discovered that there appear to be three different types of string comparison algorithms:

  1. Edit Distance Based
  2. Token Based
  3. Sequence Based

If you’d like to read more about the three types of algorithm’s I suggest reading: String similarity — the basic know your algorithms guide!

For my use-case, I decided that an Edit Distance Based algorithm would be the quickest strategy to implement myself, so that’s what I’m going with and would like to present below. The actual code that I will end up using in my app may feature a few modifications for speed, such as shortening the number of iterations before returning a result, but what I have so far should be a good start if you need something quick and easy:

var string = [];
string[0] = 'CALM 03/26 PURCHASE';
string[1] = 'CANVA* 02644-3020257 03/28 PURCHASE HTTPSCANVA.CO DE';
string[2] = 'VZWRLSS*PRPAY AUTOPAY 03/19 PURCHASE';
string[3] = 'WWW.NORDVPN.COM HTTPSWWW.NORD';
var findMe = 'CALM 02/26 PURCHASE INTERNET';
function calculateSimilarity(aString, bString) {
var matchingCharacters = 0;
var totalCharacters;
if (aString.length >= bString.length) {
totalCharacters = aString.length;
} else {
totalCharacters = bString.length
}
var shortestStringLength;
if (aString.length < bString.length) {
shortestStringLength = aString.length;
} else if (bString.length < aString.length) {
shortestStringLength = bString.length;
} else {
shortestStringLength = aString.length;
}
for (var i = 0; i < shortestStringLength; i++) {
if (aString[i] === bString[i]) {
matchingCharacters++;
}
}
var percentSimilar = matchingCharacters / totalCharacters;
return percentSimilar;
}
console.log(calculateSimilarity(findMe, string[0]).toString());
console.log(calculateSimilarity(findMe, string[1]).toString());
console.log(calculateSimilarity(findMe, string[2]).toString());
console.log(calculateSimilarity(findMe, string[3]).toString());
 

Working with ISO 8601 dates in Python Part II

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

If you happen to have stumbled upon this post I apologize, I’m not going to be doing a lot of explaining here. Rather, I really just wanted to post this little snippet of code for my own reference so I don’t lose it! But hey, maybe you’ll find it useful too…

from datetime import date, datetime
now = datetime.now()
print(now)
now_iso_8601 = now.isoformat()
print(now_iso_8601)
import time as time_
current_time = time_.time()
print(current_time)
# date.isoformat() vs date.fromisoformat
date_from_iso_format = date.fromisoformat('1987-02-06')
print(date_from_iso_format)
date_isoformat = date.isoformat(now)
print(date_isoformat)
# REFERENCE: https://topherpedersen.blog/2019/07/12/how-to-get-the-current-year-month-and-day-as-integers-in-python-3-using-the-datetime-module/
# REFERENCE: https://www.w3schools.com/python/python_datetime.asp
year = now.year
month = now.month
day = now.day
print("One month ago...")
one_month_ago = date(year, month - 1, day)
print(one_month_ago)
print("One year ago...")
one_year_ago = date(year - 1, month, day)
print(one_year_ago)
print("Two years ago...")
two_years_ago = date(year - 2, month, day)
print(two_years_ago)
view raw date_playground.py hosted with ❤ by GitHub
 

How to Push a Previous Commit Back to the Top of the Master Branch in GitHub

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Having trouble trying to push an old commit back to the top of your master branch in GitHub? This can be quite the doozy! I find myself frequently wanting to return my GitHub repository back to a previous state, and Git does not make this easy to do! What usually happens for me is that whenever I’m ready to finally push the previous commit back to the master branch, I end up running into a merge conflict. Ouch.

So, this is what you need to do if you find yourself in this situation. First, checkout the old commit that you want to restore your repository to (replace ‘c0mm1t1d’ with the commit id you want to checkout):

$ git checkout c0mm1t1d

Then create a new branch to work with:

$ git switch -c my-new-branch

$ git push origin my-new-branch

For good measure, make a small change to your new branch and commit the change. I suggest adding a comment or some other superficial change so you can verify that your repo has been updated exactly the way you like. Then commit the change:

$ git add -A

$ git commit -m "bug fix"

$ git push origin my-new-branch

Now time for the magic! We will merge our new branch back into the master branch using the “favor ours merge strategy” to ensure that our new branch is favored over the old branch should any merge conflicts arise:

$ git merge -s ours master

$ git checkout master

$ git merge my-new-branch

$ git push origin master

Alight, so there’s one last key piece of information I must mention: At some point you are going to be prompted to “Please enter a commit message to explain why this merge is necessary”, and then will get stuck inside of some awful vi/vim editor which you can’t get out of. Here’s what you need to do! Enter a short message explaining the merge, press ESCAPE, type:

:wq
Then press ENTER again to exit the prompt. And that’s it! Your repo and master branch are back in business.

 

Trouble getting Realm Version 5.0.0 to Work in React-Native? Here’s The Solution…

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Welcome back dear internet friend!

So it looks like you’re having trouble getting Realm Version 5.0.0 in your React-Native app? It’s not your fault! For the past several hours I’ve found myself banging my head against the wall with the same problem, and here’s what I’ve discovered: Realm has not updated their JavaScript documentation to match version 5.

That’s right, while the documentation may “say” that it’s for version 5, as of April 2020 the code samples are all for version 4 and likely will not work if you’ve gone ahead and installed version 5. The fix for this is simple however. Just go ahead and uninstall version 5, and then install version 4 and all shall be well!

$ npm uninstall --save realm

$ npm install --save realm@4.0.0-beta.0

$ cd ios

$ pod install

$ cd ../

Then try running you’re app again…

$ npx react-native run-android

Furthermore, I think the reason behind this mistake by the Realm team is that they are primarily focused on iOS first, and Android second, and React-Native/NodeJS last! So if you are doing native iOS development you probably should be using version 5 if you’re starting a new project. But if you’re a React-Native or Node developer, you definitely want to be using version 4 until they updated their docs.

 

React Native UI Component Not Updating when Redux Store Changes

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Having trouble getting your React Native UI components to update after the state of your Redux store has changed? Your problem is likely related to the brave new world of ES6 and the Functional Programming Paradigm. Specifically, in your Redux reducers you need to make sure you are keeping everything “immutable”. The simplest way to fix this if the spread operator (…) isn’t working for you is to try wrapping values that you wish to copy in JSON.parse and JSON.stringify methods. I know it’s very ugly, but it is an extremely effective method for fixing issues with React, Redux, and UI components that are failing to sync with state changes in your Redux store. For example, take a look at the two reducers below. The first example shows a broken reducer from one of my applications. And the second example shows the same reducer after I fixed it using the method described above:

Broken Reducer

const initialState = {
snacks: []
}
const logCaloriesReducer = (state, action) => {
// check for state undefined to prevent
// redux from crashing app on load
if (typeof state === 'undefined') {
return initialState;
}
switch(action.type) {
case 'LOG_CALORIES':
const updatedState = { ...state };
const indexOfNextSnack = updatedState.snacks.length;
const newSnack = {
calories: action.payload.calories,
time: action.payload.time
};
updatedState.snacks[indexOfNextSnack] = newSnack;
return updatedState;
default:
return state;
return state;
}
};
view raw broken_reducer.js hosted with ❤ by GitHub

Working Reducer

const initialState = {
snacks: []
}
const logCaloriesReducer = (state, action) => {
// check for state undefined to prevent
// redux from crashing app on load
if (typeof state === 'undefined') {
return initialState;
}
switch(action.type) {
case 'LOG_CALORIES':
const newState = JSON.parse(JSON.stringify(state));
const indexOfNextSnack = state.snacks.length;
const newSnack = {
calories: action.payload.calories,
time: action.payload.time
};
newState.snacks[indexOfNextSnack] = newSnack;
return newState;
default:
return state;
return state;
}
};
view raw working_reducer.js hosted with ❤ by GitHub
 

How to Build a Simple Web Server in Golang to Serve Static HTML Pages

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Quick little demonstration of how to server static HTML pages using Golang. This example assumes both your index.html and webserver.go files are in the same directory:

// REFERENCE (Simple Static Web Server in Go): https://stackoverflow.com/questions/26559557/how-do-you-serve-a-static-html-file-using-a-go-web-server
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.ListenAndServe(":3000", nil)
}
view raw webserver.go hosted with ❤ by GitHub
<!DOCTYPE html>
<html>
<body>
<h1>My Super Sweet Homepage</h1>
<button onclick="doStuff()">CLICK HERE</button>
<script>
function doStuff() {
alert("do stuff!");
}
</script>
</body>
</html>
view raw index.html hosted with ❤ by GitHub

Need routes to other pages? Check out this example I have posted on GitHub: SimpleGolangWebServer

Need to serve up JSON instead of HTML? Check out this example by Tom Hudson: simple-json-api.go

 

The Best React-Native/Redux Tutorial

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

This post is sort of just a bookmark for myself, as I know I will undoubtedly need to reference the React-Native/Redux boilerplate for years to come. However, maybe someone else out there on the internet will find this helpful as well! TLDR: Aligator.io has the best quickstart tutorial with all of the boilerplate code that you need to get up and running with Redux in a React-Native project.

Now for some more opinion and a quick rant: All of the boilerplate code that is necessary to get up and running with Redux is its biggest drawback. Personally, I hate boilerplate code. Maybe that’s because I’m a pretty messy and disorganized person, but I can’t stand having to write and learn tons and tons of boilerplate code just to get started with something. Take the Django web framework for instance. The first Python web-dev project I ever undertook I initially turned to Django after coming from a PHP background. But after 4 pages of “Getting Started” material I still had not gotten to “hello, world.” So I ended up ditching Django in favor of the much simpler Flask web framework, and haven’t looked back since.

With Redux I find myself in a similar predicament. I need some sort of state management for my React projects as the built in system just isn’t cutting it anymore, but is Redux really the best option? A much simpler solution is Unstated. So if you’ve made it this far in my post and are having similar feelings, I suggest checking out Unstated.

The only problem with Unstated is that employers are probably using Redux (or possibly MobX-State-Tree). So you kind of have to learn it, just because that’s what everyone seems to be using. In essence, I don’t think Redux is so bad. Actions, reducers, and a store. Pretty straight forward right? It sounds simple, but in practice it’s probably the most painful part of programming in React.