- Fix irrelevant react memory leak warning in a few cases
- Fix a bug in
useStore
with lack of store updates triggered by react hooks in children components
- Allow
as const
typescript assertion foruseStoreMap
keys. It helps us to infer type forfn
arguments
import React from 'react'
import {createStore} from 'effector'
import {useStoreMap} from 'effector-react'
type User = {
username: string
email: string
bio: string
}
const users = createStore<User[]>([
{
username: 'alice',
email: '[email protected]',
bio: '. . .',
},
{
username: 'bob',
email: '[email protected]',
bio: '~/ - /~',
},
{
username: 'carol',
email: '[email protected]',
bio: '- - -',
},
])
export const UserProperty = ({id, field}: {id: number; field: keyof User}) => {
const value = useStoreMap({
store: users,
keys: [id, field] as const,
fn: (users, [id, field]) => users[id][field] || null,
})
return <div>{value}</div>
}
In typescript versions below 3.4, you can still use an explicit type assertion
import React from 'react'
import {createStore} from 'effector'
import {useStoreMap} from 'effector-react'
type User = {
username: string
email: string
bio: string
}
const users = createStore<User[]>([
{
username: 'alice',
email: '[email protected]',
bio: '. . .',
},
{
username: 'bob',
email: '[email protected]',
bio: '~/ - /~',
},
{
username: 'carol',
email: '[email protected]',
bio: '- - -',
},
])
export const UserProperty = ({id, field}: {id: number; field: keyof User}) => {
const value = useStoreMap({
store: users,
keys: [id, field] as [number, keyof User],
fn: (users, [id, field]) => users[id][field] || null,
})
return <div>{value}</div>
}
as const in typescript docs
- Fix bug with additional rerender in case of
useStore
argument change
- Fix flow typings for
useStoreMap
- Add
merge
for merging events
import {createEvent, merge} from 'effector'
const foo = createEvent()
const bar = createEvent()
const baz = merge([foo, bar])
baz.watch(v => console.log('merged event triggered: ', v))
foo(1)
// => merged event triggered: 1
bar(2)
// => merged event triggered: 2
- Add
split
for pattern-matching over events
import {createEvent, split} from 'effector'
const message = createEvent()
const messageByAuthor = split(message, {
bob: ({user}) => user === 'bob',
alice: ({user}) => user === 'alice',
})
messageByAuthor.bob.watch(({text}) => {
console.log('[bob]: ', text)
})
messageByAuthor.alice.watch(({text}) => {
console.log('[alice]: ', text)
})
message({user: 'bob', text: 'Hello'})
// => [bob]: Hello
message({user: 'alice', text: 'Hi bob'})
// => [alice]: Hi bob
/* default case, triggered if no one condition met */
const {__: guest} = messageByAuthor
guest.watch(({text}) => {
console.log('[guest]: ', text)
})
message({user: 'unregistered', text: 'hi'})
// => [guest]: hi
- Allow
clearNode
to automatically dispose all related intermediate steps
import {createEvent, clearNode} from 'effector'
const source = createEvent()
const target = source.map(x => {
console.log('intermediate step')
return x
})
target.watch(x => console.log('target watcher'))
source()
// => intermediate step
// => target watcher
clearNode(target)
source() // ~ no reaction ~
-
Fix promise warning for effects
-
Add
effect.finally
import {createEffect} from 'effector'
const fetchApi = createEffect({
handler: n =>
new Promise(resolve => {
setTimeout(resolve, n, `${n} ms`)
}),
})
fetchApi.finally.watch(response => {
console.log(response)
})
await fetchApi(10)
// => {status: 'done', result: '10 ms', params: 10}
// or
// => {status: 'fail', error: Error, params: 10}
- Add types for createEvent with config instead of string
- Add types for createEffect with config instead of string
- Add
event.filterMap
as new alias forevent.filter(fn)
- Remove
extract
,withProps
,is.*
re-exports
- Removed unstable_createStoreProvider
Vue adapter for effector 20
- Add
useStoreMap
hook to select part from a store. Motivation
import {createStore} from 'effector'
import {useStore, useStoreMap} from 'effector-react'
import React from 'react'
import ReactDOM from 'react-dom'
const User = ({id}) => {
const user = useStoreMap({
store: user$,
keys: [id],
fn: (users, [id]) => users[id],
})
return (
<div>
{user.name} ({user.age})
</div>
)
}
const UserList = () => useStore(userID$).map(id => <User id={id} key={id} />)
const user$ = createStore({
alex: {age: 20, name: 'Alex'},
john: {age: 30, name: 'John'},
})
const userID$ = user$.map(users => Object.keys(users))
ReactDOM.render(<UserList />, document.getElementById('root'))
- Add support for
event.filter
with common predicate functions
import {createEvent} from 'effector'
const event = createEvent()
// that event will be triggered only when fn returns true
const filtered = event.filter({
fn: x => x > 0,
})
filtered.watch(x => console.log('x =', x))
event(-2) // nothing happens
event(2) // => x = 2
- Fix typescript typings #116
To indicate the stability of the project, we adopting semantic versioning and happy to announce version 19.0.0 for all packages. And to make the transition easier, that release contains no breaking changes; simple replacement of "^0.18.*" to "^19.0.0" is safe for sure ☄️
- Implement event
store.updates
, representing updates of given store. Use case: watchers, which will not trigger immediately after creation (unlikestore.watch
)
import {createStore, is} from 'effector'
const clicksAmount = createStore(0)
is.event(clicksAmount.updates) // => true
clicksAmount.watch(amount => {
console.log('will be triggered with current state, immediately, sync', amount)
})
clicksAmount.updates.watch(amount => {
console.log('will not be triggered unless store value is changed', amount)
})
- Allow
clearNode
to erase information from the node itself, in addition to the existing opportunity to erase subscribers (thanks @artalar)
- Add support for passing multiply items at once in
store.reset
import {createStore, createEvent} from 'effector'
const firstTrigger = createEvent()
const secondTrigger = createEvent()
const target = createStore(0).reset(firstTrigger, secondTrigger)
-
Add support for
createEvent
andcreateEffect
with config (see next code example) -
Add
.pending
property for effects
import {createEffect} from 'effector'
import {createComponent} from 'effector-react'
import React from 'react'
const fetchApi = createEffect({
handler: n => new Promise(resolve => setTimeout(resolve, n)),
})
fetchApi.pending.watch(console.log)
const Loading = createComponent(
fetchApi.pending,
(props, pending) => pending && <div>Loading...</div>,
)
fetchApi(5000)
it's a shorthand for common use case
import {createEffect, createStore} from 'effector'
const fetchApi = createEffect()
//now you can use fetchApi.pending instead
const isLoading = createStore(false)
.on(fetchApi, () => true)
.on(fetchApi.done, () => false)
.on(fetchApi.fail, () => false)
- Introduce
sample
. Sample allows to integrate rapidly changed values with common ui states
import {createStore, createEvent, sample} from 'effector'
import {createComponent} from 'effector-react'
import React from 'react'
const tickEvent = createEvent()
const tick = createStore(0).on(tickEvent, n => n + 1)
setInterval(tickEvent, 1000 / 60)
const mouseClick = createEvent()
const clicks = createStore(0).on(mouseClick, n => n + 1)
const sampled = sample(tick, clicks, (tick, clicks) => ({
tick,
clicks,
}))
const Monitor = createComponent(sampled, (props, {tick, clicks}) => (
<p>
<b>tick: </b>
{tick}
<br />
<b>clicks: </b>
{clicks}
</p>
))
const App = () => (
<div>
<Monitor />
<button onClick={mouseClick}>click to update</button>
</div>
)
- Add babel plugin for automatic naming of events, effects and stores (useful for identifying resources with SSR)
- Add babel plugin for automatic displayName for react components
import {createStore, createEvent} from 'effector'
import {createComponent} from 'effector-react'
import React from 'react'
const title = createStore('welcome')
console.log('store.shortName', title.shortName)
// store.shortName title
const clickTitle = createEvent()
console.log('event.shortName', clickTitle.shortName)
// store.shortName clickTitle
const Title = createComponent(title, (props, title) => <h1>{title}</h1>)
console.log('Component.displayName', Title.displayName)
// Component.displayName Title
Plugins are available out from a box
.babelrc
:
{
"plugins": ["effector/babel-plugin", "effector/babel-plugin-react"]
}
- Add support for passing events and effects to watchers
import {createStore, createEvent} from 'effector'
const updates = createEvent()
const state = createStore(0)
state.watch(updates)
- Improve execution order for sync effects
- Improve typescript typings for createApi (#102)
- Add initial props factory to
createComponent
import {users} from './feature'
const UserItem = createComponent(
initialProps => users.map(users => users[initialProps.id]),
(_, user) => {
return <div>{user.username}</div>
},
)
const UserList = createComponent(users, (_, users) => {
return users.map(user => <TodoItem key={user.id} id={user.id} />)
})
- Implicitly convert objects to
createStoreObject
increateComponent
const deposit = createEvent()
const username = createStore('zerobias')
const balance = createStore(0)
const Profile = createComponent(
{username, balance},
(_, {username, balance}) => {
return (
<div>
Hello, {username}. Your balance is {balance}
<button onClick={deposit}>Deposit</button>
</div>
)
},
)
- Add
mounted
andunmounted
events to components created bycreateComponent
import {counter, increment} from './feature'
const Counter = createComponent(counter, (_, state) => {
return (
<div>
{state}
<button onClick={increment}>+</button>
</div>
)
})
Counter.mounted.watch(({props, state}) => {
counter.on(increment, s => s + 1)
})
Counter.unmounted.watch(({props, state}) => {
counter.off(increment)
})
- Replace
useLayoutEffect
withuseIsomorphicLayoutEffect
to support server-side rendering
- Replace
useEffect
withuseLayoutEffect
inuseStore
hook to response to state changes immediately
- Optimize combined stores: no intermediate steps no more
import {createStore, createEvent, createStoreObject, combine} from 'effector'
const field = createStore('')
const isEmpty = field.map(value => value.length === 0)
const isTooLong = field.map(value => value.length > 12)
const isValid = combine(
isEmpty,
isTooLong,
(isEmpty, isTooLong) => !isEmpty && !isTooLong,
)
const updateField = createEvent('update field value')
field.on(updateField, (state, upd) => upd.trim())
createStoreObject({
field,
isEmpty,
isTooLong,
isValid,
}).watch(data => {
console.log(data)
})
// => {field: '', isEmpty: true, isTooLong: false, isValid: false}
updateField('bobby')
// => {field: 'bobby', isEmpty: false, isTooLong: false, isValid: true}
-
Use the new kernel. Provide improved eventual consistency: any side effects will be triggered only after performing all pure computations
-
Add
is
namespace for all type validators
import {createStore, createEvent, is} from 'effector'
const store = createStore('value')
const event = createEvent('some event')
is.store(store) // => true
is.event(store) // => false
is.unit(store) // => true
is.store(event) // => false
is.event(event) // => true
is.unit(event) // => true
is.store(null) // => false
is.event(null) // => false
is.unit(null) // => false
-
Add
clearNode
to break references and subscriptions between events, stores, etc -
Add support for custom datatypes by making
step
constructors,createNode
andlaunch
functions public
import {createNode, launch, step, createStore} from 'effector'
const target = createStore(0)
target.watch(n => console.log('current n = ', n))
// => current n = 0
const customNode = createNode({
scope: {max: 100, lastValue: -1, add: 10},
child: [target], // you can forward later as well
node: [
step.compute({
fn: (arg, {add}) => arg + add,
}),
step.filter({
fn: (arg, {max, lastValue}) => arg < max && arg !== lastValue,
}),
step.compute({
fn(arg, scope) {
scope.lastValue = arg
return arg
},
}),
],
})
launch(customNode, 3)
// => current n = 13
launch(customNode, 95)
// no reaction, as 95 + 10 > 100
launch(customNode, 5)
// => current n = 15
launch(customNode, 5)
// no reaction, as we filtered it out with step.filter
- Fix
fromObservable
, ensure it works withredux
as a typical library withSymbol.observable
support
import {fromObservable} from 'effector'
import * as redux from 'redux'
const INCREMENT_STATE = 'INCREMENT_STATE'
const reduxStore = redux.createStore((state = 1, action) => {
switch (action.type) {
case INCREMENT_STATE:
return state + 1
default:
return state
}
})
const updateEvent = fromObservable(reduxStore)
updateEvent.watch(state => {
console.log('redux state = ', state)
})
reduxStore.dispatch({type: INCREMENT_STATE})
// => redux state = 1
- Fix
version
, now it always equals version in package.json
import {version} from 'effector'
console.log(version)
// => 0.18.6
- Add support forwarding to effects
import {createEffect, createEvent, forward} from 'effector'
const trigger = createEvent()
const sideEffect = createEffect('side-effect', {
async handler(args) {
await new Promise(rs => setTimeout(rs, 500))
console.log('args: ', args)
},
})
forward({
from: trigger,
to: sideEffect,
})
trigger('payload')
// ~ after 500 ms
// => args: payload
- Add version variable to public exports
import {version} from 'effector'
console.log(version)
-
Add effect handler to domain 4c6ae8
-
Add
Unit<T>
as common interface implemented byEvent
,Effect
andStore
-
Add
isStore
,isEvent
,isEffect
andisUnit
validators
import {createStore, createEvent, isStore, isEvent, isUnit} from 'effector'
const store = createStore('value')
const event = createEvent('some event')
isStore(store) // => true
isEvent(store) // => false
isUnit(store) // => true
isStore(event) // => false
isEvent(event) // => true
isUnit(event) // => true
isStore(null) // => false
isEvent(null) // => false
isUnit(null) // => false
- Add extended
createStore
with config
import {createStore} from 'effector'
const store = createStore('value', {
name: 'value store',
})
-
Publish babel-plugins
-
Improve naming for chrome performance timeline
-
Fix typescript typings #45
-
Fix
event.prepend
bug #35
-
Fix webpack usage issue. To prevent this in a future, webpack integration test was added.
-
Improve typescript typings for
createApi
. This code example became type checked
import {createStore, createApi} from 'effector'
const text = createStore('')
const {addMessage, cut} = createApi(text, {
addMessage: (text, message) => text + `\n` + message
cut: (text, {fromIndex, size}) => text.slice(fromIndex, fromIndex + size),
})
- Add umd bundle to npm. Therefore, you can use cdn to include library without bundlers
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/effector.umd.js"></script>
</head>
<body>
<script>
const header = document.createElement('h1')
document.body.appendChild(header)
const text = effector.createStore('hello')
text.watch(str => (header.innerHTML = str))
</script>
</body>
</html>
- Add
forward
: common function for forwarding updates and events
import {forward} from 'effector'
const unsubscribe = forward({
from: Event | Store,
to: Event | Store | Effect,
})
- add support for storages in
store.on
import {createStore} from 'effector'
const name = createStore('name')
const counter = createStore(0).on(name, (count, name) => count++)
- Allow to pass
{handler: Function}
as second argument tocreateEffect
import {createEffect} from 'effector'
const callApi = createEffect('call api', {
async handler(url) {
const res = await fetch(url)
return res
},
})
- Make
effect.use
return the same effect instead of void (ability to chain method calls)
import {createEffect} from 'effector'
const callApi = createEffect('call api').use(url => fetch(url))
- Log events into Chrome devtools performance timeline
- Add notifications about errors inside computation chain
- Add
store.defaultState
property - effector-react: Add
createComponent
- Make
withProps
static function - Make effect return plain promise
- Add Gate
import {type Gate, createGate} from 'effector-react'
const AppGate = createGate('app')
const MainPageGate = AppGate.childGate('main page')
export default ({isLoading, meta}) => (
<div>
Application
<AppGate isLoading={isLoading} />
{!isLoading && (
<div>
Main page
<MainPageGate meta={meta} />
</div>
)}
</div>
)
AppGate.state.watch(({isLoading}) => isLoading)
- Keep and replay the whole domain history for every new hook
- Add domain hooks for handle new events, effects or stores in domain.
import {createDomain} from 'effector'
const mainPage = createDomain('main page')
mainPage.onCreateEvent(event => {
console.log('new event: ', event.getType())
})
mainPage.onCreateStore(store => {
console.log('new store: ', store.getState())
})
const mount = mainPage.event('mount')
// => new event: main page/mount
const pageStore = mainPage.store(0)
// => new store: 0
- Improve TypeScript typings
- Add ability to use createEvent, createEffect and createDomain without arguments (omit name)
- Fix wrong order of effect names
- Add
createWrappedDomain
to watch all nested events and updates - Add
extract
to watch only part of nested storages - Deprecate
.epic
method (library supports symbol-observable, so assumed thatmost.from(event)
orObservable.Of(store)
covered all use cases)
- effector-react: Add check for mounting of store consumer
- Add
effect.use.getCurrent()
method to get current used function - Improve type inference in flow typing for
createStoreObject
- Improve public ts and flow typings
- Fix effector-react typings
- Build with node 6 target, add engine field to package.json
- Add warning dependency
- Memoize store.map and store updates
- Added sync graph reduction engine (it's internal)
- Added store updates memoization
- Introduced effector-react
- Removed most-subject dependency
- New api
- Add AVar: low-level interface for asynchronous variables
- Clean up builds before publishing
- Add types dir into npm build
- Add independent
createStore
method - Replace console.warn with console.error in warnings
- Make reducers full-featured store elements (add
.get()
,.set(x)
and.map(fn)
methods) - Add observable declaration to effects, events and reducers, which allow interop in this way:
from(effect)
- Build via rollup
- New module architechture
- Exclude coverage from npm build
- Rename
mill
tocollect
- Rename
joint
tocombine
- Remove source files from npm release
- Add support for sync functions in
.use
- breaking Rename config option
effectImplementationCheck
tounused
- Fix overriding of flow modules
- breaking Removed
rootDomain
alias forcreateRootDomain
- Fixed duplication of
typeConstant
events - Added sync event propagation
- Catching of watch function errors
- Added warning to port errors
- Added type aliases
DomainAuto
,EventAuto
andEffectAuto
- Added
mill
fluent "AND" reducer combinator
import {mill, type MillType, type Reducer} from 'effector'
type A = 'foo'
type B = 'bar'
declare var reducerA: Reducer<A>
declare var reducerB: Reducer<B>
const tuple: MillType<A, B> = mill()
.and(reducerA)
.and(reducerB)
const union: Reducer<{
a: A,
b: B,
staticField: string,
}> = tuple.joint((a: A, b: B) => ({
a,
b,
staticField: 'its ok',
}))
- Added hot reload support for root domains
- Added support for dispatching halt action
import {createHaltAction} from 'effector'
store.dispatch(createHaltAction()) //This store will be unsubscribed
First stable version
Proof of concept