Giter Club home page Giter Club logo

effector's Introduction

☄️ Effector

Reactive state manager

npm version Codeship Status for zerobias/effector Build Status Join the chat at https:// .im/effector-js/community PRs welcome License

Table of Contents

Introduction

Effector is an effective multi store state manager for Javascript apps (React/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.

Detailed comparison with other state managers will be added soon

Effector follows five basic principles:

  • Application stores should be as light as possible - the idea of adding a store for specific needs should not be frightening or damaging to the developer. Stores should be freely combined - the idea is that the data that an application needs can be distributed statically, showing how it will be converted during application operation.
  • Application stores should be freely combined - data that the application needs can be statically distributed, showing how it will be converted in runtime.
  • Autonomy from controversial concepts - no decorators, no need to use classes or proxies - this is not required to control the state of the application and therefore the api library uses only functions and simple js objects
  • Predictability and clarity of API - A small number of basic principles are reused in different cases, reducing the user's workload and increasing recognition. For example, if you know how .watch works for events, you already know how .watch works for stores.
  • The application is built from simple elements - space and way to take any required business logic out of the view, maximizing the simplicity of the components.

Effector Diagram

Installation

npm install --save effector

Or using yarn

yarn add effector

Additional packages:

Examples

Three following examples that will give you a basic understanding how the state manager works:

Increment/decrement

import {createStore, createEvent} from "effector";
import {createComponent} 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 = createComponent(counter, (props, counter) => (
  <>
    <div>{counter}</div>
    <button onClick={increment}>+</button>
    <button onClick={decrement}>-</button>
    <button onClick={resetCounter}>reset</button>
  </>
));

const App = () => <Counter />;

Hello world with events and nodejs

const {createEvent} = require('effector')

const messageEvent = createEvent('message event (optional description)')

messageEvent.watch(text => console.log(`new message: ${text}`))

messageEvent('hello world')
// => new message: hello world

Storages and events

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

Demo

Edit Effector-react example Basic example

Edit Effector-react example SSR example

More examples/demo you can check here

Core concepts

import type {Domain, Event, Effect, Store} from 'effector'

Domain

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.event('mount')
// => new event: main page/mount

const pageStore = mainPage.store(0)
// => new store: 0

Event

Event is an intention to change state.

  const event = createEvent() // unnamed event
  const onMessage = createEvent('message') // named event

  const socket = new WebSocket('wss://echo.websocket.org')
  socket.onmessage = (msg) => onMessage(msg)

  const data = onMessage.map(msg => msg.data).map(JSON.parse)

  // Handle side effects
  data.watch(console.log)

Effect

Effect is a container for async function. It can be safely used in place of the original async function. The only requirement for function - Should have zero or one argument

  const getUser = createEffect('get user')
    .use((params) => {
      return fetch(`https://example.com/get-user/${params.id}`)
        .then(res => res.json())
    })

  // subscribe to promise resolve
  getUser.done.watch(({result, params}) => {
    console.log(params) // {id: 1}
    console.log(result) // resolved value
  })

  // subscribe to promise reject (or throw)
  getUser.fail.watch(({error, params}) => {
    console.error(params) // {id: 1}
    console.error(error) // rejected value
  })

  // you can replace function anytime
  getUser.use(() => promiseMock)

  // call effect with your params
  getUser({id: 1})

  const data = await getUser({id: 2}) // handle promise

Store

Store is an object that holds the state tree. There can be multiple stores.

// `getUsers` - is an effect
// `addUser` - is an event
const defaultState = [{ name: Joe }];
const users = createStore(defaultState)
  // subscribe store reducers to events
  .on(getUsers.done, (oldState, payload) => payload)
  .on(addUser, (oldState, payload) => [...oldState, payload]))

// subscribe side-effects
const callback = (newState) => console.log(newState)
users.watch(callback) // `.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 is their compositions:

// `.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)

Learn more

API

import {
  createEvent,
  createEffect,
  createDomain,
  createStore,
  createStoreObject,
} from 'effector'

Sponsors

Thank you to all our sponsors 🙏

Contributors


Dmitry

💬 💻 📖 💡 🤔 🚇 ⚠️

andretshurotshka

💬 💻 📖 📦 ⚠️

Sergey Sova

📖 💡

Arutyunyan Artyom

📖 💡

Ilya

📖

License

MIT

effector's People

Contributors

artalar avatar gitter-badger avatar goodmind avatar kelin2025 avatar komar0ff avatar mg901 avatar miyaokamarina avatar sergeysova avatar zerobias avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.