RoyalIcing / react-organism

Dead simple React state management to bring pure components alive
https://react-organism.now.sh/
MIT License
223 stars 3 forks source link

Call other handlers #1

Closed RoyalIcing closed 7 years ago

RoyalIcing commented 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 }),
  increment: ({ commands: { fetchAPI } }) =>
    fetchAPI('/increment', { method: 'post' })
    .then(Promise.resolve(
      ({ count }) => ({ count: count + 1 })
    ))
})

Consider commands & messages like Elm? See also: https://guide.elm-lang.org/architecture/effects/

RoyalIcing commented 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)
      ])
    }
  }
})