import React from 'react' ; import { createStore , IsLoadingFunc , StoreActions , useStore } from '../../dist' ; import { optimisticActions as optimisticActionsMiddleware } from '../../dist/middlewares' ; import OptimisticView from './OptimisticView' ; import { Status } from './types' ; type State = { value : string ; status : Status ; } ; type Actions = { sendAction : ( willFail : boolean ) => Promise < string > ; resetValue : ( ) => void ; } ; export type OptimisticViewProps = State & Actions & { isLoading : IsLoadingFunc < Actions > ; } ; export const getInitialState = ( ) : State => ( { value : 'Initial value' , status : 'paused' , } ) ; export const optimisticActions = { sendAction : { preEffects : ( { s } ) => ( { ... s , status : 'running' } ) , getPromise : ( { args : [ willFail ] } ) => new Promise ( ( res , rej ) => setTimeout ( willFail ? rej : res , 5000 ) ) , optimisticEffects : ( { s } ) => ( { ... s , value : 'Optimistic value' } ) , errorEffects : ( { s } ) => ( { ... s , status : 'errored' } ) , effects : ( { s } ) => ( { ... s , value : 'Success value' , status : 'succeeded' , } ) , } , resetValue : ( s ) => ( { ... s , value : 'Initial value' , status : 'paused' } ) , } ; const store = createStore ( getInitialState , optimisticActions , { notifyError : ( ) => { } } , [ optimisticActionsMiddleware ( ) , ] ) ; const CounterContainer = ( ) => { const { state , actions , isLoading } = useStore ( store ) ; return < OptimisticView { ... state } { ... actions } isLoading = { isLoading } / > ; } ; export default CounterContainer ;