Skip to content

Instantly share code, notes, and snippets.

View JaysonChiang's full-sized avatar

Jayson JaysonChiang

View GitHub Profile
@JaysonChiang
JaysonChiang / gist:a01df90d60e1a1ecb315388321816d71
Created November 16, 2021 14:41
Implement onFocus/onBlur by onClick
const DropDownList = () => {
const [focus, setFocus] = useState(false);
const ref = useRef(null);
useEffect(() => {
const listener = (event) => {
if ( ref.current && event.target && ref.current.contains(event.target)) {
return;
}
@JaysonChiang
JaysonChiang / api.ts
Last active February 28, 2024 00:18
Example of Axios with TypeScript
import axios, { AxiosError, AxiosResponse } from 'axios';
import token from './somewhere';
interface Todo {
id: string;
title: string;
}
interface User {
id: string;
@JaysonChiang
JaysonChiang / api.js
Last active May 24, 2023 13:02
optimize api.js
import axios from 'axios';
import { token } from './somewhere';
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.interceptors.request.use((config) => {
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
@JaysonChiang
JaysonChiang / api.js
Last active June 12, 2021 10:30
improve with catch api.js
import axios from 'axios';
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.interceptors.response.use(res => res.data
, error => {
const { data, status, config } = error.response;
switch(status) {
case 400:
console.error(data);
@JaysonChiang
JaysonChiang / api.js
Last active June 12, 2021 10:32
basic api.ts
import axios from 'axios';
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
const api = {
getData: () => axios.get('/todos/1')
};
export default api;
const subject = {
observers: [],
subscribe(fn) {
this.observers.push(fn)
},
notify(arg) {
this.observers.forEach(fn => fn(arg));
}
}
const subject = {
observers: [],
subscribe(observer) {
this.observers.push(observer)
},
notify(message) {
this.observers.forEach(observer => observer.update(message));
}
}
const joe = {
update(message) {
console.log(`Joe receive ${message}`);
}
}
const jason = {
update(message) {
console.log(`Jayson read ${message}`);
}
@JaysonChiang
JaysonChiang / TodoList.tsx
Created March 2, 2021 01:21
useSelector with DefaultRootState
import { useSelector } from './useSelector';
const TodoList: React.FC = () => {
const { todos } = useSelector((state) => state.todos);
return (
<ul>
{todos.map((todo) => (
<li>{todo}</li>
))}
@JaysonChiang
JaysonChiang / TodoList.tsx
Created March 2, 2021 00:54
useSelector without DefaultRootState
import { useSelector } from 'react-redux';
const TodoList: React.FC = () => {
const { todos } = useSelector((state) => state.todos);
// Property 'todos' does not exist on type 'DefaultRootState'.
return (
<ul>
{todos.map((todo) => (
<li>{todo}</li>