Using Typescript with React Native

ref – https://blog.logrocket.com/using-typescript-with-react-native/

source download

Open up a terminal

npx react-native init TypeScriptTemplate –template react-native-template-typescr

Once we’ve finished creating the React Native typescript template project, let’s go ahead with running the project.

cd into the ios folder:

npm run ios

You’ll probably run into some issues.

TroubleShooting

First make sure you delete the pod.lock file, and pod folder. Then reinstall all the pod dependencies by going:

pod install

In /Users/{your name}/Desktop/{your project}/node_modules/react-native/scripts/generate-spec.sh

put this line at the top:

When I installed a new version of xCode, there were two installations. The default was still pointing to the old version, so I followed the direction on the terminal and removed the old one.

Last but not least, make sure you restart your computer so the changes to the environment can take place.

Starting Development

Create a folder structure like src/components in the root directory and create a Header.tsx component in the components folder.

src/components/Header.tsx

React.FC means functional component. We want to create a React Functional Component that takes in a parameter with type Props

Props is defined as an interface with the property title and of type string

This means that in our App.tsc, we will be using it like so:

Thus, we can use instantiate this functional component and use typescript to type the prop property. In other words, because we’re using TypeScript, we are now able to define what our component should take in, how it should take it in, and how many to take.

The benefit of doing it this way is that we get better IntelliSense and some validation when we’ll use the component ( e.g. when the title is not passed to the component, there’s going to be an instant error).

Thus, if we were to use Header without putting any prop named title in, we’d get some errors:

If you tried to assign a number (or any other data type that isn’t a string) you’ll get a different error. This is TypeScript trying to help you catch bugs before they happen.

Adding Items

Create a new component, AddItem.tsx, to your /src/components folder and paste the code below:

Getting and Setting our Array of Items

First, we want to create interface IItem. It is a type that says I must have two strings, one called item, the other called quantity.

We will declare an array of this IItem, where each element contains an item string and quantity string.

Next we see type Props.

It has shoppingList, which gets an array [] of type IItem, as mentioned previously. This automatically GETS the data.

In order to SET an array of IItem, React guarantees that dispatch function identity is stable and won’t change on re-renders.

https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down

1) Thus, we must declare type React.Dispatch because this property will be called inside of a button handler. It calls a set function, which is defined by React.SetStateAction.

2) Thus, we want to declare SetStateAction:

It’s an action state that initializes to iItem [].

How The iItem array is used

create functional component called AddItem
type Props says the first is called ‘shoppingList’, that
must be of type IItem array which Sets
the second is called ‘shoppingList’, which is an array of iItem

Hence, in App.tsx, it must be used this way:

How AddItem Functional Component is created

String is used in our JSX to contain the item name from a textfield. Once it has been entered, and add btn as pressed, our addItem function will see if this item exists.

Same for quantity.

simple styles for the textfields

Showing the Items

Create another file in /src/components named Item.tsx.

We import type from iItem in AddItem file. That way we force the parameter type to be of type iItem. After all, we are displaying the item and need the data passed in to conform to that type.

and the CSS theme for it

The app should look like this:

Node JS with mySQL using Sequelize and Express

ref – https://www.esparkinfo.com/node-js-with-mysql-using-sequelize-express.html

source download

setup MySQL

Make sure your mySQL is installed on a mac like this:
http://chineseruleof8.com/code/index.php/2016/05/17/install-mysql-and-use-terminal-to-use-it/’

When you set up your mySQL, create a database called testdb

Node JS

$ mkdir nodejs-express-sequelize-mysql
$ cd nodejs-express-sequelize-mysql

name: (nodejs-express-sequelize-mysql)
version: (1.0.0)
description: Node.js Rest Apis with Express, Sequelize & MySQL.
entry point: (index.js) server.js
test command:
git repository:
keywords: nodejs, express, sequelize, mysql, rest, api
author: esparkinfo
license: (ISC)

Setting Up Express JS Web Server

in the root directory, create server.js

Configuring MySQL Database & Sequelize

In the root directory, create a config folder.
In that folder, create db.config.js

Note – The first five parameters are intended for MySQL. The pool parameter is optional and is deployed in the Sequelize connection pool config. The parameters are explained below.

max -maximum number of connections permissible in a pool
min – minimum number of connections permissible in a pool
idle – maximum time, in terms of milliseconds, that a connection can be held idly before being released
acquire – maximum time, in terms of milliseconds, that the pool seeks to make the connection before an error message pops up on screen

Sequelize

In the root directory, create a models folder

In the models folder, create index.js by entering the following code :

models/index.js

In MySQL databases, this model represents tutorial tables. The columns are automatically generated, a few of which are id, description, createdAt, and published.

tutorial.model.js

Then in server.js, we require this model, and use

What happens is that in in model/index.js, we allocated a new Sequelize object and initialized it with a mysql database connection using our db configuration. We import this functionality into our server.js. We call the sync function with the force option set to true in order to DROP TABLE IF EXISTS before trying to create the table – if you force, existing tables will be overwritten.

You’ll be signed in as db user root with your password before this takes place, so make sure its all correct.

Controller

Routes import Controllers and Controller’s exported functions create, find, update, delete, etc.
Controller’s create will first error check all the incoming parameters, then uses model. Thus controllers are the middleman.

Routes

If the client sends a request for an endpoint via an HTTP request such as POST, DELETE, PUT, or GET, the user must determine how the server responds.

Such a response from the server is possible by setting up the below routes:

/api/tutorials: GET, POST, DELETE
/api/tutorials/:id: GET, PUT, DELETE
/api/tutorials/published: GET
To create a tutorial.routes.js inside the app/routes folder, the user performs the following steps:

In order to use routes, remember to put

in server.js, right above code for port.

Hence, our server.js has code for routes, which routes to middleman controller, which then uses models to make changes to the database.

In the end, your server should look like this:

server.js

Using Postman to test

In Postman, new tab:

POST on http://localhost:8080/api/tutorials

Body, raw, then select JSON.

In the body:

In your database terminal, to see what you’ve inserted, get all results:

select * from tutorials;

Get all tutorials

Get specific tutorial

GET on http://localhost:8080/api/tutorials/2

Finding All Tutorials where Title=”node”

GET on http://localhost:8080/api/tutorials?title=tut

Find all published posts

GET on http://localhost:8080/api/tutorials/published

Delete depending on request param id

DELETE on http://localhost:8080/api/tutorials/2

MySQL in Docker

ref – https://www.factorialcomplexity.com/blog/how-to-run-mysql-on-macos-with-docker

You’ll see your local-mysql app entry appear on your docker.

Click on the CLI button

Now you’re in.

type:
show databases

to see existing database

Computed Values in Vue

Todo methods vs computed properties

3. Computed Property
Computed properties are also functions but they are different from methods. They run only once per page load, and it will re-run only if any of it’s dependent variable changes.

The difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as message has not changed, multiple access to the reversedMessage computed property will immediately return the previously computed result without having to run the function again.

In comparison, a method invocation will always run the function whenever a re-render happens.

Vue 3 with Typescript – 6 to 7

Computed Values

ref – https://www.youtube.com/watch?v=TwN36HU-NQM
hyrule-jobs-6 demo

JobsList.vue

Now that w have orderedJobs data structure, let’s use it in our template:

Hylia Font & Final Styles

ref – https://www.youtube.com/watch?v=6n4myAZwdxg

Vue 3 with Typescript – 4 to 5

download demo

Types and Props

inside components folder, create JobsList.vue

type “ts” + click on bottom option

There should be boilerplate code. Let’s add template and style.

Now we declare and import in file App.vue.
then put it inside of components object to use it.

get rid of our placeholder template code and replace it with our component. The jobs data that we have in setup should now be passed inside the props as well:

Implementing JobList

We make an object for props property. Then declare jobs property. This property is the options of how jobs is declared. We say it is required, and of type Array.

In our template, we put the necessary html and a ul. For the li, we cycle through jobs using v-for. It needs a unique key prop. We have it in jobs data array as id.

JobsList.vue

If you were to run the site, you’ll see the list of titles.

Next we declare props for the component. If you were to use say Array for prop jobs, it doesn’t know what properties are available for each job because in props jobs declaration, we only declared it
as Array.

JobsList.vue

Hence, no code suggestions when you use it in template.

The solution is that we need to type our props better.

Using Vetur for template interpolation

JobsList.vue

Now, you’ll be able to see different options when you try to access properties of job object.
In settings, make sure Vetur > Experimental: Template Interpolation Service is checked

JobsList.vue

Functions

ref – https://www.youtube.com/watch?v=usSBsgWNUZk

We want jobs to be reordered by salary, title..etc.

add event handler to each of them.

create file types/OrderTerm.ts

first create this function

App.vue

First look at order reference. We pass it into JobList so that when a button is pressed, an event happens, and manipulates the order ref.
The change in order ref can be evaluated in JobList.

Since it has been set up in App.vue, we must implement this in JobList.vue

We declare order prop.

components/JobList.vue

in the template:

App.vue

Vue 3 with Typescript – 1 to 3

Part 1

ref – https://www.youtube.com/watch?v=JfI5PISLr9w

Why Use Typescript
– type errors are caught at compile time
– easier to read the code
– better debugging

vue create hyrule-jobs

Use space bar to select manually select features.

Want to use TypeScript
use 3.x
DO NOT want class style component syntax
DO want to use Babel
Pick linter: Basic
Lint on Save
In dedicated config files

cd hyrule-jobs

Code . to open it with Visual Studio Code

npm run serve

File layout

Open the src folder.
notice main.ts

It is a typescript file.

shims-vue.d.ts – tells typescript all about vue files so it can better understand single file components
don’t change any of it.

tsconfig.json – typescript compiler

Look at src/App.vue
script tag has lang attribute for ts. That’s because we’re using typescript inside of it.

Go into components, delete HelloWorld.vue

Go into assets, delete logo.png

In App.vue, remove all code in template tag. Leave a div with text ‘Link’ in it.
remove HelloWorld import
remove HelloWorld from components

remove styles from style tags.

App.vue

create assets > global.css

Register css in main.ts

npm run serve

You will see text.

Part 2

ref – https://www.youtube.com/watch?v=UDAVj_vlAr8

Declare own data ‘name’ and display it in our template:

App.vue

create methods to set name:

Test by running browser again.

Using Union Types

For data property, we must use type casting. If it was a single type, it gets inferred. But what if we want to use multiple type such as number OR string?

create changeAge method:

duplicate button, and change it for age. Use number 30 for the parameter. Can also use string “30” for the parameter.

Part 3

ref – https://www.youtube.com/watch?v=H-hXNym2CK8

https://stackoverflow.com/questions/61452458/ref-vs-reactive-in-vue-3

  • reactive() only takes objects, NOT JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined)
  • ref() is calling reactive() behind the scenes
  • Since reactive() works for objects and ref() calls reactive(), objects work for both BUT, ref() has a .value property for reassigning, reactive() does not have this and therefore CANNOT be reassigned

therefore…

Use ref() when..

  • it’s a primitive (for example ‘string’, true, 23, etc)
  • it’s an object you need to later reassign (like an array)

ref() is good for objects that need to be reassigned, like an array.

If we were to do the same with reactive, we’d have to reassign property posts

reactive() Use-Case
A good use-case for reactive() is a group of primitives that belong together:

the code above feels more logical than

Let’s try grouping name and age in an object and passing it to reactive. Notice that its more natural when we use the variable state? Even better if we change it to personState, because properties name and age group together better.

We then set properties like so:

using refs

Create custom type

create folder called types in src
in types folder, create jobs.ts

job.ts

use it inside App component

src/App.vue

Check the output