Managing application state in production applications is crucial. and with finite state machine we can have error-free applications.
export const authMachine =
createMachine({
id: 'authMachine',
initial: 'LOGGED_OUT',
context: {
userProfile: null,
cognitoUserProfile: null,
platform: undefined,
},
states: {
LOGGED_OUT: {
on: {
login: {
target: 'LOGGED_IN',
actions: assign({
cognitoUserProfile: (context, event) => event.data,
}),
},
},
},
LOGGED_IN: {
initial: 'USER_PROFILE_CHECK',
states: {
USER_PROFILE_CHECK: {
invoke: {
// check if user is added to DB
src: context => {
return new Promise(async (resolve, reject) => {
},
onDone: {
target: 'USER_PROFILE_PRESENT',
actions: assign({
userProfile: (context, event) => event.data,
}),
},
// if not added transit to USER_PROFILE_ABSENT
onError: {
target: 'USER_PROFILE_ABSENT',
actions: (context, event) => {
console.log('USER_PROFILE_ABSENT', event.value);
},
},
},
},
USER_PROFILE_PRESENT: {},
USER_PROFILE_ABSENT: {
invoke: {
// Add user to DB
src: () => {},
// if added set machine context and transit to USER_PROFILE_PRESENT
onDone: {target: 'USER_PROFILE_PRESENT', action: () => {}},
},
},
},
on: {
logout: {
target: 'LOGGED_OUT',
actions: assign(() => {
return {
userProfile: null,
cognitoUserProfile: null,
};
}),
},
},
},
},
});