CSS Note: Unit conversion from relative to pixels

Just a lil note on unit conversion from relative to pixels

・Each property has an itinital value if not declared or there is no inheritance ・Browsers specify a root font-size for each page(usually 16px ) ・Percentages and reltavie units are always converted to pixels

Percentage %

・measured relative to parent's font-size when used for font-size
・measured relative to parent's length if used for lengths

em

・measured relative to parent's font-size when used for font-size
・measure relative to CURRENT font-size when used for lengths

rem

・ALWAYS measured relative to the document's root font-size

vh and vw

・percentage measurements of the viewport's height and width

Creating repository for existing project on Github

A lil note on how to make a new repository on GitHub of an existing local project

  1. Create a new repository on GitHub.
  2. Open your terminal
  3. cd to the project you want to create on Github
  4. Initialize the local directory as a Git repository git init
  5. Add the files to your new local repository. git add .
  6. Commit the added files git commit -m "first commit"
  7. Copy the HTTPS URL of your newly created repository and add the URL to the following command git remote add origin <remote repository URL>

then just push to GitHub git push origin master

React Hook: useState Example

*useState notes for me, myself, and i

  • use useState to add state to function components

class component and function component comparison

class component

class Example extends React.Component {
    constructor() {
        super();

        this.state = {
            displayName: '',
            email: '',
        };
    }

    handleChange = (event) => {
        const { name, value } = event.target;

        this.setState({ [name]: value });
    };

    render() {
        const { displayName, email } = this.state;
        return (
            <div className='App'>
                <input
                    type='text'
                    value={displayName}
                    name='displayName'
                    placeholder='username'
                    onChange={this.handleChange}
                    required
                ></input>
                <input
                    type='text'
                    value={email}
                    name='email'
                    placeholder='email'
                    onChange={this.handleChange}
                    required
                ></input>
            </div>
        );
    }}

export default Example;

function component

const Example = () => {
    const [userCredentials, setUserCredentials] = useState({
        displayName: '',
        email: '',
    });

    const handleChange = (event) => {
        const { name, value } = event.target;

        setUserCredentials({ ...userCredentials, [name]: value });
    };

    const { displayName, email } = userCredentials;

    return (
        <div className='App'>
            <input
                type='text'
                value={displayName}
                name='displayName'
                placeholder='username'
                onChange={handleChange}
                required
            ></input>
            <input
                type='text'
                value={email}
                name='email'
                placeholder='email'
                onChange={handleChange}
                required
            ></input>
        </div>
    );
};

export default Example;

Redux-Saga example

*redux-saga notes for me myself and i

Redux-saga are for asynchronous actions with side-effects

install

npm i redux-saga

root.reducer.js

import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';

import userReducer from './user/user.reducer.js';

const rootReducer = combineReducers({
    user: userReducer,
});

export default rootReducer;

store.js

import createSagaMiddleware from 'redux-saga';
import rootSaga from './root-saga.js';

const sagaMiddleware = createSagaMiddleware();
const middleWares = [sagaMiddleware]
const store = createStore(rootReducer, applyMiddleware(...middleWares));
sagaMiddleware.run(rootSaga);

export default store;

root-saga.js

import { all, call } from 'redux-saga/effects';
import { userSagas } from './user/user.sagas.js';

export default function* rootSaga() {
    yield all([call(shopSagas), call(userSagas), call(cartSagas)]);
}

user.types.js

const UserActionTypes = {
    EMAIL_SIGN_IN_START: 'EMAIL_SIGN_IN_START',
    SIGN_IN_SUCCESS: 'SIGN_IN_SUCCESS',
    SIGN_IN_FAILURE: 'SIGN_IN_FAILURE',
};

export default UserActionTypes;

user.actions.js

import UserActionTypes from './user.types.js';

export const emailSignInStart = (emailAndPassword) => ({
    type: UserActionTypes.EMAIL_SIGN_IN_START,
    payload: emailAndPassword,
});

export const signInSuccess = (user) => ({
    type: UserActionTypes.SIGN_IN_SUCCESS,
    payload: user,
});

export const signInFailure = (error) => ({
    type: UserActionTypes.SIGN_IN_FAILURE,
    payload: error,
});

user.reducer.js

import UserActionTypes from './user.types';

const INITIAL_STATE = {
    currentUser: null,
    error: null,
};

const userReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case UserActionTypes.SIGN_IN_SUCCESS:
            return {
                ...state,
                currentUser: action.payload,
                error: null,
            };

        case UserActionTypes.SIGN_IN_FAILURE:
            return {
                ...state,
                error: action.payload,
            };

        default:
            return state;
    }
};

export default userReducer;

TypeScript Basic Notes

*Some TypeScript notes for me, myself, and I

Typescript

  • adds types
  • write cleaner code
  • avoid unneccessary error

install

npm install --save-dev typescript

compile .ts to .js

command line: tsc hoge.js

or

command line: tsc hoge.ts --watch or tsc hoge.ts -w // no need to recompile hoge.ts every time file is saved

or

tsc --init // the whole project is managed by typescript which creates a tsconfig.json
tsc // will compile the whole project
tsc --watch // recompile every changed file with save

assigning types

variable + : + type

ex:
let hoge: string;
function hoge(message: string) {
   console.log(message);
}

Core Types

number string boolean

objects

const hoge: object {} // only knows that its an object cant get individual elements in objects (hoge.name)

const hoge: { name: string, age: number } // this can get individual elements

ex:

const person: {
    name: string;
    age: number;
} = {
    name: ‘Max’,
    age: 42,
};
console.log(person.name);

arrays

const hoge: string[] // array of strings

ex:
let favHobbies: string[];
favHobbies = [‘Swimming’, 'Golf'];

tuple - array with fixed length and type

  - const hoge: [number, string]; // but push can be implemented

enum

let favHobbies: string[];
favHobbies = [‘Swimming’, 'Golf'];

enum Role {
    ADMIN,
    READ_ONLY,
    AUTHOR,
}

const person: {
    name: string;
    age: number;
    hobbies: string[];
    role: Role;
} = {
    name: ‘Max’,
    age: 42,
    hobbies: favHobbies,
    role: Role.ADMIN,
};

Union types

  • expect multiple types
  • function hoge(input1: number | string, input2: number | string)

Literal Types

  • union type but is specific value
  • function hoge(input1: ‘Max’| ‘Matt’)

Type Aliases

  • define your own types
  • type Combinable = sting | number; function hoge(input: Combinable)

Function Types

  • defines the return type
  • describe which type of function specifically use somewhere (parameter, callback, variable )
  • function hoge(num: number): number { return num; }
type Combinable = string | number;
type ConversionDescriptor = 'as-number' | 'as-string';

function combine(
    input1: Combinable,
    input2: Combinable,
    resultConversion: ConversionDescriptor
) {
    let result;
    if (
        (typeof input1 === 'number' && typeof input2 === 'number') ||
        resultConversion === 'as-number'
    ) {
        result = +input2 + +input2;
    } else {
        result = input1.toString() + input2.toString();
    }

    return result;
}

const combinedHoges = combine('32', '23', 'as-number');
console.log(combinedHoges);

const combinedAges = combine(34, 43, 'as-number');
console.log(combinedAges);

const combnedNames = combine('Max', 'Anderson', 'as-string');
console.log(combnedNames);

** some tsconfig.json notes

  • "exclude": ["hoge.ts"] // typescript will ignore hoge.ts
  • "node_modules" // ignore node_modules already in default

  • "include": ["hoge.ts"] // typescript will only think hoge.ts is typescript, so will need to add all typescript files

  • compilerOptions

    • "noEmitOnError": true, // will not compile any ts while there is an error

Redux Thunk

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.

install

npm install redux-thunk
npm install redux-logger // logs when action is dispatched in developer tool console

store.js

import thunk from 'redux-thunk';

const middleWares = [];

// use logger middleware when in development mode
if (process.env.NODE_ENV === 'development') {
    middleWares.push(logger);
}

const store = createStore(rootReducer, applyMiddleware(...middleWares));

hoge.actionTypes.js

const HogeActionTypes = {
    FETCH_HOGE_START: `FETCH_HOGE_START`,
    FETCH_HOGE_SUCCESS: 'FETCH_HOGE_SUCCESS',
    FETCH_HOGE_FAILURE: 'FETCH_HOGE_FAILURE',
};

export default HogeActionTypes;

hoge.actions.js

import HogeActionTypes from ‘HogeActionTypes.js’

export const fetchHogeSuccess = (hoge) => ({
    type: HogeActionTypes.FETCH_HOGE_SUCCESS,
    payload: hoge,
});

export const fetchHogeFailure = (error) => ({
    type: HogeActionTypes.FETCH_HOGE_FAILURE,
    payload: error,
});

export const fetchHogeStart = () => ({
    type: HogeActionTypes.FETCH_HOGE_START,
});

export const fetchHogeStartAsync = () => {
    return (disptach, getState) => {
    dispatch(fetchHogeStart)();
    fetchHoge()
        .then((hoge) => { dispatch(fetchHogeSuccess(hoge)); })
        .catch((error) => { dispatch(fetchHogeFail(error)); } )
   }    
}

hoge.reducers.js

import HogeActionTypes from ‘HogeActionTypes.js’

const INITIAL_STATE = {
    hoge: null,
    isFetching: false,
    errorMessage: undefined,
};

const hogeReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case HogeActionTypes.FETCH_HOGE_START:
            return {
                ...state,
                isFetching: true,
            };

        case HogeActionTypes.FETCH_HOGE_SUCCESS:
            return {
                ...state,
                isFetching: false,
                hoge: action.payload,
            };

        case HogeActionTypes.FETCH_HOGE_FAILURE:
            return {
                ...state,
                isFetching: false,
                errorMessage: action.payload,
            };

        default:
            return state;
    }
};

export default hogeReducer;

hoge.js

import { fetchHogeStartAsync } from ‘hoge.actions.js’

const fetchHoge = () => {
    fetchHogeStartAsync();
}


const mapDispatchToProps = (dispatch) => ({
    fetchHogeStartAsync: () => dispatch(fetchHogeStartAsync()),
})

Redux Persistor

*Saves redux state to local or session storages

Local Storage ・Data is stored in tabs and windows ・The data will not expire. ・Data remains after browser restart

Session Storage ・Data is stored in current tab only ・Data remains after browser restart but not closing and reopening

install

npm i redux-persist

root-reducers.js

import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // for local storage
import storage from 'redux-persist/lib/storage/session'; // for session storage

const persistConfig = {
    key: 'root',
    storage,
    whitelist: ['cart'],
};

const rootReducer = combineReducers({
});

export default persistReducer(persistConfig, rootReducer);

store.js

import { persistStore } from 'redux-persist';

const store = createStore(rootReducer, applyMiddleware(...middleWares));

const persistor = persistStore(store);

export { store, persistor };

index.js

import { persistor } from './redux/store.js';
import { PersistGate } from 'redux-persist/integration/react';

ReactDOM.render(
    <Provider store={store}>
        <PersistGate persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>,
    document.getElementById('root')
);