Closed RoyalIcing closed 7 years ago
// organisms/Counter.js
import makeOrganism from 'react-organism'
import Counter from './components/Counter'
import fetchAPI from './fetchAPI'
export default makeOrganism(Counter, {
initial: () => ({ count: 0 }),
incrementLocally: () => ({ count }) => ({ count: count + 1 }),
decrementLocally: () => ({ count }) => ({ count: count - 1 }),
increment: ({ handlers }) =>
handlers.incrementLocally()
.then(() => fetchAPI('/increment', { method: 'post' }))
.catch(error => Promise.all([
handlers.decrementLocally(),
{ apiError: error }
]))
})
// organisms/Counter.js
import makeOrganism from 'react-organism'
import Counter from './components/Counter'
import fetchAPI from './fetchAPI'
export default makeOrganism(Counter, {
initial: () => ({ count: 0 }),
incrementLocally: () => ({ count }) => ({ count: count + 1 }),
decrementLocally: () => ({ count }) => ({ count: count - 1 }),
increment: async ({ handlers }) => {
await handlers.incrementLocally()
try {
await fetchAPI('/increment', { method: 'post' })
}
catch (error) {
await handlers.decrementLocally()
return { apiError: error }
}
}
})
// organisms/Counter.js
import makeOrganism from 'react-organism'
import Counter from './components/Counter'
import fetchAPI from './fetchAPI'
export default makeOrganism(Counter, {
initial: () => ({ count: 0 }),
incrementLocally: () => ({ count }) => ({ count: count + 1 }),
decrementLocally: () => ({ count }) => ({ count: count - 1 }),
setAPIError: (props, error) => ({ apiError: error }),
increment: async ({ handlers }) => {
await handlers.incrementLocally()
try {
await fetchAPI('/increment', { method: 'post' })
}
catch (error) {
await Promise.all([
handlers.decrementLocally(),
handlers.setAPIError(error)
])
}
}
})
Consider commands & messages like Elm? See also: https://guide.elm-lang.org/architecture/effects/