Giter Site home page Giter Site logo

logical's Introduction

logical

Predictable yet Expressive State Management for TypeScript Applications

⚠️ logical is in BETA, use at your own risk.

Docs

First, define what your application state looks like.

type State = {
    count: number;
};

const initialState: State = {
    count: 0,
};

Then, list all the events that can happen in your app, and how they change the state.
(If you're coming from redux, these are your actions and your reducer in one.)

const logic = createLogic<State>()({
    increase: (amount: number) => state => void (state.count += amount),
    decrease: (amount: number) => state => void (state.count -= amount),
    reset: () => state => void (state.count = 0),
    multiplyThenAdd: (mult: number, add: number) => state => void (state.count = state.count * mult + add),
});
What's the deal with the `void` prefix? It ensures that the assignment following it does not return a value. You could also wrap the assignment in curly braces if you prefer:
const logic = createLogic<State>()({
    increase: (amount: number) => state => {
        state.count += amount;
    },
    // ...
});
Why the double parentheses? That's the only way I could get TypeScript to properly infer but not constrain the type you're passing to `createLogic()` here (ie. 'partial type argument inference'). See https://stackoverflow.com/questions/62490272/how-can-i-have-typescript-infer-the-value-for-a-constrained-generic-type-when-sp for example.

Finally, create your store and start dispatching events.

const store = new Store<State>(initialState);
const dispatcher = store.getDispatcher()(logic);

dispatcher.increase(10);
console.log(store.get().count); // 10

dispatcher.decrease(3);
console.log(store.get().count); // 7

dispatcher.multiplyThenAdd(3, 5);
console.log(store.get().count); // 26

dispatcher.reset();
console.log(store.get().count); // 0

Of course, you can also subscribe to the store's changes:

store.subscribe(newValue => console.log(`The latest store value is ${newValue}`));

This also means you can use it as a Svelte store:

<script lang="ts">
    import { store } from './app.ts';
</script>

<div>The current count is: {$store.count}</div>

What about side effects? ⚡️

Right. Remember how you weren't supposed to return anything in your logic's event handlers? That's because with logical, that is reserved for side effects!

First, define your state as usual:

type State = {
    value: number;
    status: 'initial' | 'pending' | 'finished' | `failed: ${string}`;
};

const initialState: State = {
    value: 0,
    status: 'initial',
};

Then describe your side effects, along with their success and failure event handlers:

const sideEffects = createSideEffects<State>()({
    // Each side effect consists of...
    fetchRandomNumber: [
        // a function returning a promise,
        () =>
            fetch('https://www.randomnumberapi.com/api/v1.0/random/')
                .then(response => response.json())
                .then(results => results[0]),

        // a success event handler,
        randomNumber => state => {
            state.value = randomNumber;
            state.status = 'finished';
        },

        // and a failure event handler.
        exception => state => void (state.status = `failed: ${exception.message}`),
    ],
});

You can trigger the side effect by returning it from an event handler:

const logic = createLogic<State>()({
    onButtonClicked: () => state => {
        state.status = 'pending';
        return sideEffects.fetchRandomNumber();
    },
});

Make sure to pass your side effects to getDispatcher():

const dispatcher = store.getDispatcher()(logic, sideEffects);
button.addEventListener('click', () => dispatcher.onButtonClicked());

You can even await the dispatching of events that run side effects:

const store = new Store(initialState);
console.log(store.get().value); // 0

const dispatcher = store.getDispatcher()(logic, sideEffects);

await dispatcher.onButtonClicked();
console.log(store.get().value); // 42 if I am really lucky

Or return multiple side effects in an array:

const logic = createLogic<State>()({
    init: () => () => [sideEffects.attachEventListeners(), sideEffects.setupAutosave()],
    // ...
});

Notes

I am test-driving logical in my pet project 10queue. Check out the code to get a feel for the usage.

logical's People

Contributors

endreymarcell avatar

Watchers

James Cloos avatar  avatar

logical's Issues

Add support for debugging

The store should accept an optional debug flag which would make it log every event and side-effect.

allow void side effects

It's uncomfortable to have to type out return Promise.resolve() for side effects which do not return a value and do not employ promises internally. Upon execution, the store should inspect the return value of side effects, and if the value is not a promise, it should return Promise.resolve() automatically.

Better error message if `sideEffects` is not passed to `getDispatcher()`

If you have side effects but forget to pass them to getDispatcher() then triggering a side effect results in a cryptic error message about "something$Success" not being defined. We could easily detect such a case and give a more helpful error message.

(Or better yet, somehow ensure with the type system that if your logic returns a side effect at some point than your getDispatcher is also receiving the sideEffects?)

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.