Last active
July 24, 2023 22:47
-
-
Save muhamed-didovic/1061368579172603701e0c443257b448 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const loadFromDatabase = async () => { | |
// Your database loading logic goes here | |
// For example, you can use an API call to fetch the data from your backend | |
// Make sure to return the fetched data or handle errors accordingly | |
return 'from1'; | |
return await yourDatabaseAPI.loadFormData(); | |
}; | |
const saveToDatabase = async (formData) => { | |
// Your database saving logic goes here | |
// For example, you can use an API call to save the data to your backend | |
// Make sure to return the result or handle errors accordingly | |
return ''; | |
return await yourDatabaseAPI.saveFormData(formData); | |
}; | |
const fetchMachine = Machine( | |
{ | |
id: 'dynamicStateExample', | |
initial: 'loading', | |
context: { | |
targetState: null, | |
}, | |
states: { | |
loading: { | |
invoke: { | |
src: 'fetchTargetStateFromDB', | |
onDone: { | |
actions: assign({ | |
targetState: (_, event) => event.data, // Save the fetched target state to the context | |
}), | |
}, | |
// onError: 'error', | |
}, | |
on: { | |
'': [ | |
// Check the fetched target state and transition accordingly | |
{ target: 'loggedIn', cond: (context) => context.targetState === 'loggedIn' }, | |
{ target: 'loggedOut', cond: (context) => context.targetState === 'loggedOut' }, | |
// If the fetched target state is unknown or invalid, transition to the 'error' state | |
// { target: 'error' }, | |
], | |
}, | |
}, | |
loggedIn: { | |
// Your "loggedIn" state configuration here | |
}, | |
loggedOut: { | |
// Your "loggedOut" state configuration here | |
}, | |
error: { | |
// Your "error" state configuration here | |
}, | |
}, | |
}, | |
{ | |
services: { | |
fetchTargetStateFromDB: () => { | |
// Simulate fetching target state from the DB (replace this with your actual fetch code) | |
return new Promise((resolve, reject) => { | |
// Replace the setTimeout with your actual DB fetch call | |
setTimeout(() => { | |
const targetStateFromDB = 'loggedOut'; // Simulating fetched state as 'loggedIn', replace this with your fetched data | |
resolve(targetStateFromDB); | |
// In case of an error, use `reject(error)` instead of `resolve(targetStateFromDB)` | |
}, 2000); | |
}); | |
}, | |
}, | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment