Skip to content

Instantly share code, notes, and snippets.

@leegeunhyeok
Last active January 28, 2023 17:52
Show Gist options
  • Save leegeunhyeok/dc906b3d7602e702310e29bb9059d060 to your computer and use it in GitHub Desktop.
Save leegeunhyeok/dc906b3d7602e702310e29bb9059d060 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const TAG = 'GlobalMachine';
const AsyncStorage = localStorage;
Machine(
{
id: TAG,
initial: 'idle',
context: {
user: null,
},
states: {
idle: {
entry: ['onIdle'],
on: {
AUTO_LOGIN: 'loading',
},
},
loading: {
id: 'loading',
entry: ['onLoading'],
after: {
DEFAULT_TIMEOUT: 'unauthorized',
},
invoke: {
src: 'loadUser',
onDone: {
target: 'authorized',
actions: 'setUser',
},
onError: 'unauthorized',
},
},
authorized: {
initial: 'idle',
entry: ['onAuthorized'],
on: {
LOGOUT: 'unauthorized',
REFRESH: '.refreshing',
},
states: {
idle: {},
refreshing: {
invoke: {
src: 'loadUser',
onDone: {
target: 'idle',
actions: 'setUser',
},
onError: '#unauthorized'
},
},
},
},
unauthorized: {
id: 'unauthorized',
initial: 'idle',
entry: ['onUnauthorized', 'removeUser'],
invoke: {
src: 'cleanup',
},
on: {
LOGIN: {
target: '.validating',
},
},
states: {
idle: {},
validating: {
invoke: {
src: 'saveUser',
onDone: '#loading',
onError: 'idle',
},
},
},
},
},
},
{
actions: {
setUser: assign({ user: (_context, event) => event.data }),
removeUser: assign({ user: (_context, _event) => null }),
onIdle: () => {
console.log(TAG, 'onIdle');
},
onLoading: () => {
console.log(TAG, 'onLoading');
},
onAuthorized: () => {
console.log(TAG, 'onAuthorized');
},
onUnauthorized: () => {
console.log(TAG, 'onUnauthorized');
},
},
services: {
loadUser: async () => {
const stringifiedUser = await AsyncStorage.getItem('user');
if (!stringifiedUser) {
throw new Error('user is not exist');
}
return JSON.parse(stringifiedUser);
},
saveUser: async (_context, event) => {
await AsyncStorage.setItem('user', JSON.stringify(event.user));
},
cleanup: () => AsyncStorage.clear(),
},
delays: {
DEFAULT_TIMEOUT: 3 * 1000,
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment