Security News
Opengrep Emerges as Open Source Alternative Amid Semgrep Licensing Controversy
Opengrep forks Semgrep to preserve open source SAST in response to controversial licensing changes.
The state manager
Effector is an effective multi-store state manager for Javascript apps (React/React Native/Vue/Node.js), that allows you to manage data in complex applications without the risk of inflating the monolithic central store, with clear control flow, good type support and high capacity API. Effector supports both TypeScript and Flow type annotations out of the box.
npm install --save effector
# or
yarn add effector
React
npm install --save effector effector-react
# or
yarn add effector effector-react
Vue
npm install --save effector effector-vue
# or
yarn add effector effector-vue
Svelte
Svelte works with effector out from a box, no additional packages needed. See word chain game application written with svelte and effector.
CDN
For additional information, guides and api reference visit our documentation site
Package | Version | Size |
---|---|---|
effector | ||
effector-react | ||
effector-vue |
effector
to your project's home pageYou can try effector in our repl
Code sharing, Typescript and react supported out of the box; and of course, it built with effector
import {createStore, createEvent} from 'effector'
import {useStore} from 'effector-react'
const increment = createEvent('increment')
const decrement = createEvent('decrement')
const resetCounter = createEvent('reset counter')
const counter = createStore(0)
.on(increment, state => state + 1)
.on(decrement, state => state - 1)
.reset(resetCounter)
counter.watch(console.log)
const Counter = () => {
const value = useStore(counter)
return <div>{value}</div>
}
const App = () => {
const value = useStore(counter)
return (
<>
<Counter />
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={resetCounter}>reset</button>
</>
)
}
const {createEvent} = require('effector')
const messageEvent = createEvent()
messageEvent.watch(text => console.log(`new message: ${text}`))
messageEvent('hello world')
// => new message: hello world
const {createStore, createEvent} = require('effector')
const turnOn = createEvent()
const turnOff = createEvent()
const status = createStore('offline')
.on(turnOn, () => 'online')
.on(turnOff, () => 'offline')
status.watch(newStatus => {
console.log(`status changed: ${newStatus}`)
})
// for store watchs callback invokes immediately
// "status changed: offline"
turnOff() // nothing has changed, callback is not triggered
turnOn() // "status changed: online"
turnOff() // "status changed: offline"
turnOff() // nothing has changed
useList
hookguard
Event is an intention to change state.
import {createEvent} from 'effector'
const send = createEvent() // unnamed event
const onMessage = createEvent('message') // named event
const socket = new WebSocket('wss://echo.websocket.org')
socket.onmessage = msg => onMessage(msg)
socket.onopen = () => send('{"text": "hello"}')
const onMessageParse = onMessage.map(msg => JSON.parse(msg.data))
onMessageParse.watch(data => {
console.log('Message from server ', data)
})
send.watch(data => {
socket.send(data)
})
Effect is a container for async function. It can be safely used in place of the original async function.
import {createEffect} from 'effector'
const fetchUserReposFx = createEffect({
async handler({name}) {
const url = `https://api.github.com/users/${name}/repos`
const req = await fetch(url)
return req.json()
},
})
// subscribe to pending store status
fetchUserReposFx.pending.watch(pending => {
console.log(pending) // false
})
// subscribe to handler resolve
fetchUserReposFx.done.watch(({params, result}) => {
console.log(params) // {name: 'zerobias'}
console.log(result) // resolved value
})
// subscribe to handler reject or throw error
fetchUserReposFx.fail.watch(({params, error}) => {
console.error(params) // {name: 'zerobias'}
console.error(error) // rejected value
})
// subscribe to both cases
fetchUserReposFx.finally.watch(data => {
if (data.status === 'done') {
const {params, result} = data
console.log(params) // {name: 'zerobias'}
console.log(result) // resolved value
} else {
const {params, error} = data
console.error(params) // {name: 'zerobias'}
console.error(error) // rejected value
}
})
// you can replace handler anytime
fetchUserReposFx.use(requestMock)
// calling effect will return a promise
const result = await fetchUserReposFx({name: 'zerobias'})
Store is an object that holds the state tree. There can be multiple stores.
// `getUsers` - is an effect
// `addUser` - is an event
const users = createStore([{ name: Joe }])
// subscribe store reducers to events
.on(getUsers.done, (oldState, payload) => payload)
.on(addUser, (oldState, payload) => [...oldState, payload]))
// subscribe to store updates
users.watch(state => console.log(state)) // `.watch` for a store is triggered immediately: `[{ name: Joe }]`
// `callback` will be triggered each time when `.on` handler returns the new state
Most profit thing of stores.
Get smaller part of the store:
// `.map` accept state of parent store and return new memoized store. No more reselect ;)
const firstUser = users.map(list => list[0])
firstUser.watch(newState => console.log(`first user name: ${newState.name}`)) // "first user name: Joe"
addUser({name: Joseph}) // `firstUser` is not updated
getUsers() // after promise resolve `firstUser` is updated and call all watchers (subscribers)
Compose stores:
import {createStore, combine} from 'effector'
const a = createStore(1)
const b = createStore('b')
const c = combine({a, b})
c.watch(console.log)
// => {a: 1, b: "b"}
See combine
in docs
Domain is a namespace for your events, stores and effects. Domain can subscribe to event, effect, store or nested domain creation with onCreateEvent, onCreateStore, onCreateEffect, onCreateDomain(to handle nested domains) methods.
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.createEvent('mount')
// => new event: main page/mount
const pageStore = mainPage.createStore(0)
// => new store: 0
See Domain
in docs
See also worker-rpc example, which uses shared domain for effects
More articles about effector at patreon
Dmitry 💬 💻 📖 💡 🤔 🚇 ⚠️ | andretshurotshka 💬 💻 📖 📦 ⚠️ | Sergey Sova 📖 💡 💻 ⚠️ 🤔 | Arutyunyan Artyom 📖 💡 | Ilya 📖 | Arthur Irgashev 📖 💻 💡 | Igor Ryzhov 📖 💻 💡 |
Egor Guscha 📖 | bakugod 📖 💡 | Ruslan 📖 💻 🤔 ⚠️ | Maxim Alyoshin 📖 | Andrey Gopienko 📖 | Vadim Ivanov 📖 | Aleksandr Anokhin 💻 |
Anton Kosykh 💻 | Konstantin Lebedev 💡 | Pavel Tereschenko 💻 | Satya Rohith 📖 | Vladislav Melnikov 💻 | Grigory Zaripov 💻 | Marina Miyaoka 💻 |
Evgeny Zakharov 📖 | Viktor 💻 📖 ⚠️ 🤔 | Ivan Savichev 💻 🤔 | Nikita Nafranets 📖 💡 | Tauyekel Kunzhol 📖 | Andrew Laiff 📖 | Illia Osmanov 💻 🤔 |
Yan 📖 | Egor Aristov 📖 | Sozonov 📖 | Rafael Fakhreev 💻 🤔 ⚠️ | Victor 💻 🤔 📖 | Dmitrij Shuleshov 📖 | Valeriy Kobzar 💻 🚇 🤔 |
Ivan 💻 ⚠️ |
effector 20.17.2
attach
to domain effects, allowing these effects to be called within other effects when using fork
import {createDomain, attach} from 'effector'
import {fork, allSettled} from 'effector/fork'
const app = createDomain()
const addFx = app.createEffect({handler: _ => _})
const $count = app.createStore(2).on(addFx.doneData, (x, y) => x + y)
const addWithCurrent = attach({
source: $count,
effect: add,
mapParams: (params, current) => params + current,
})
const startFx = app.createEffect({
async handler(val) {
await addWithCurrent(val)
},
})
const scope = fork(app)
await allSettled(startFx, {
scope,
params: 3,
})
console.log(scope.getState(count))
// => 7
FAQs
Business logic with ease
The npm package effector receives a total of 28,952 weekly downloads. As such, effector popularity was classified as popular.
We found that effector demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Opengrep forks Semgrep to preserve open source SAST in response to controversial licensing changes.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.