Skip to content

Instantly share code, notes, and snippets.

@hypeJunction
Last active February 13, 2021 17:43
Show Gist options
  • Select an option

  • Save hypeJunction/26e5ff262e3ad60984e4e3ff369be485 to your computer and use it in GitHub Desktop.

Select an option

Save hypeJunction/26e5ff262e3ad60984e4e3ff369be485 to your computer and use it in GitHub Desktop.
const loadDraft = ({ context, setContext }) => {
console.log('Context before action', context);
const draft = localStorage.getItem('draft')
if (draft) {
setContext((state) => {
return {
...state,
message: JSON.parse(draft)
}
})
}
}
const saveDraft = ({ setContext }, { message }) => {
localStorage.setItem('draft', JSON.stringify(message))
setContext((state) => {
return {
...state,
message,
}
})
}
const sendMessage = async ({ setContext }, { message }) => {
const res = await new Promise((resolve, reject) => {
if (!message.recipient) {
return reject(new Error('Missing recipient'))
}
resolve({ uuid: uuid() })
})
localStorage.removeItem('draft')
setContext((state) => {
return {
...state,
message: {
...message,
uuid: res.uuid,
status: 'sent',
}
}
})
}
export const states = {
initializing: {
load_draft: {
handlers: [loadDraft],
target: 'writing',
},
},
writing: {
save_draft: {
handlers: [saveDraft],
target: 'writing',
},
send: {
handlers: [sendMessage],
target: 'sent',
}
},
sent: {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment