npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

dk-mobx-stateful-fn

v3.4.5

Published

Library for adding MobX observable state to async functions

Downloads

72

Readme

Library for adding MobX observable state to async functions

coverage npm license size

[!WARNING]
It's fine if you use this library from NPM package with a static versioning in case you want it for some pet-project or to test it's capabilities.

But for production use it's strongly recommended to create a fork, because I do not write Changelogs and may break / add some functionality without notice.

The purpose of this library is to simplify tracking of async function execution. It uses a pattern "function as object", adding an observable state to the function, so you could easily:

  • show loaders in your React / any framework components
  • see how much time the execution has taken
  • show error messages and names just from this function
  • easily track when all async functions have finished for SSR
  • and even cancel the function's execution (it's a fake mechanism because we cannot really cancel a Promise, but the approach here is enough for 99% apps)

Contents

Installation

Add dk-mobx-stateful-fn to package.json and install.

Usage: functions

Named functions

import { addState } from 'dk-mobx-stateful-fn';
import { autorun } from 'mobx';

function asyncFunction() {
  return new Promise((resolve) => setTimeout(resolve, 100));
}

const asyncFunctionStateful = addState(asyncFunction, asyncFunction.name);

// Now you can track this function's execution like

autorun(() => {
  console.log(JSON.stringify(asyncFunctionStateful.state));
})

asyncFunctionStateful();

Anonymous functions

In case the function does not have a name you should provide it manually, otherwise a warning will be displayed in the console.

import { addState } from 'dk-mobx-stateful-fn';

const asyncFunctionStateful = addState(() => Promise.resolve(), 'asyncFunctionStateful');

Usage: classes

Named methods (from prototype)

import { addState, TypeFnAsync } from 'dk-mobx-stateful-fn';
import { makeAutoObservable } from 'mobx';

function addStateToNamedMethod(ctx: any, fn: TypeFnAsync) {
  ctx[fn.name] = addState(fn.bind(ctx), fn.name);
}

class ClassFunctions {
  constructor() {
    // we have to exclude our functions from makeAutoObservable
    makeAutoObservable(
      this,
      { asyncFunction: false },
      { autoBind: true }
    );
    
    addStateToNamedMethod(this, this.asyncFunction);
  }

  asyncFunction() {
    // "this" is working and bound to the instance
    // console.log(this)
  
    return new Promise((resolve) => setTimeout(resolve, 100));
  };
}

Anonymous methods

import { addState } from 'dk-mobx-stateful-fn';
import { makeAutoObservable } from 'mobx';

class ClassFunctions {
  constructor() {
    // we have to exclude our functions from makeAutoObservable
    makeAutoObservable(
      this,
      { asyncFunction: false },
      { autoBind: true }
    );
    
    this.asyncFunction = addState(this.asyncFunction, 'asyncFunction');
  }

  asyncFunction = () => {
    // "this" is working and bound to the instance
    // console.log(this)
  
    return new Promise((resolve) => setTimeout(resolve, 100));
  };
}

Usage: mocks

When a mock is defined, the asyncFunctionStateful will not trigger any lifecycle and will directly return the value defined in the mock. The logic inside asyncFunction will not be executed at all. This is useful for tests or SSR.

import { addState } from 'dk-mobx-stateful-fn';
import { runInAction } from 'mobx';

function asyncFunction() {
  // WILL NOT BE EXECUTED

  return new Promise((resolve) => setTimeout(() => resolve(1), 100));
}

const asyncFunctionStateful = addState(asyncFunction, asyncFunction.name);

runInAction(() => {
  asyncFunctionStateful.state.mock = Promise.resolve(2);
});

asyncFunctionStateful().then(data => console.log(data)) // 2

Use cases

Track execution / show loaders

const MyComponent = observer(function MyComponent() {
  useEffect(() => {
    asyncFunctionStateful();
  }, []);
  
  return (
    <div>
      {asyncFunctionStateful.state.isExecuting && 'Is loading...'}
      
      {!asyncFunctionStateful.state.isExecuting && 'Loaded!'}
    </div>
  )
})

// or somewhere

autorun(() => {
  if (asyncFunctionStateful.state.isExecuting) {
    console.log(`${asyncFunctionStateful.name} is executing`);
  } else {
    console.log(`${asyncFunctionStateful.name} is idle`);
  }
})

asyncFunctionStateful();

Track execution time

const MyComponent = observer(function MyComponent() {
  useEffect(() => {
    asyncFunctionStateful();
  }, []);
  
  return (
    <div>
      {Boolean(asyncFunctionStateful.state.executionTime) && `Loading took ${asyncFunctionStateful.state.executionTime}`}
    </div>
  )
})

// or somewhere

autorun(() => {
  if (asyncFunctionStateful.state.executionTime) {
    console.log(`${asyncFunctionStateful.name} took ${asyncFunctionStateful.state.executionTime}ms to finish`);
  }
})

asyncFunctionStateful();

Show errors

const MyComponent = observer(function MyComponent() {
  useEffect(() => {
    asyncFunctionStateful();
  }, []);
  
  return (
    <div>
      {asyncFunctionStateful.state.error && `Error happened ${asyncFunctionStateful.state.error}`}
      {asyncFunctionStateful.state.errorName && `Error name is ${asyncFunctionStateful.state.errorName}`}
    </div>
  )
})

// or somewhere

autorun(() => {
  if (asyncFunctionStateful.state.error) {
    console.log(`${asyncFunctionStateful.name} failed with ${asyncFunctionStateful.state.error}`);
  }
})

asyncFunctionStateful();

Cancel execution

const MyComponent = observer(function MyComponent() {
  useEffect(() => {
    asyncFunctionStateful()
      .catch(error => {
        if (error.name === 'ACTION_CANCELED') {
          console.log('Component has been unmounted, so we will just ignore this error')
        }
      });
    
    return () => {
      asyncFunctionStateful.state.isCancelled = true;
    }
  }, []);
  
  return (
    <div></div>
  )
})

// or somewhere

autorun(() => {
  if (asyncFunctionStateful.state.errorName === 'ACTION_CANCELED') {
    console.log(`${asyncFunctionStateful.name} has been cancelled`);
  }
})

asyncFunctionStateful();

SSR

For SSR you may have an architecture where the Actions layer is separate. And this actions are executed inside React components like in examples above (but not in useEffect of course, because it's not triggered during renderToString. Maybe you use useState or ssr libs). If that's the case, SSR is as easy as that:

app.get('*', (req, res) => {
  Promise.resolve()
    .then(() => renderToString(<App />))
    
    // smth. like !actionsLayer.some(fnStateful => fnStateful.state.isExecuting)
    .then(() => waitActionsSettled())
    
    // smth. like actionsLayerNames.every(fnName => { actionsLayer[fnName] = () => Promise.resolve() })
    .then(() => mockActions())
    
    .then(() => renderToString(<App />))
    .then((html) => res.send(html))
})

If the Actions layer is not separate, but is a part of the Stores layer, you still can gather this functions in actionsLayer and use the recipe above.

This way you are not limited by implementation and can easily add SSR to your app.

Limitations

Because 1 stateful function has only 1 state, parallel execution is not supported. This code will result in inconsistency

function asyncFunction() {
  return new Promise((resolve) => setTimeout(resolve, 100));
}

const asyncFunctionStateful = addStateToNamedFunction(asyncFunction);

asyncFunctionStateful();

setTimeout(() => asyncFunctionStateful(), 1);

so state.isExecuting will become false when first call has been finished and state.executionTime will also be calculated incorrectly. You should either ensure that the stateful function has been finished like

function asyncFunction() {
  return new Promise((resolve) => setTimeout(resolve, 100));
}

const asyncFunctionStateful = addStateToNamedFunction(asyncFunction);

asyncFunctionStateful();

const interval = setInterval(() => {
  if (!asyncFunctionStateful.state.isExecuting) {
    // make the second call
    asyncFunctionStateful();
    
    clearInterval(interval);
  }
}, 10)

// or smth. like

mobx.reaction(
  () => asyncFunctionStateful.state.isExecuting,
  (isExecuting) => {
    if (!isExecuting) {
      // make the second call
      asyncFunctionStateful();
    }
  }
)

or create several stateful functions like

function asyncFunction() {
  return new Promise((resolve) => setTimeout(resolve, 100));
}

const asyncFunctionStateful = addStateToNamedFunction(asyncFunction);
const asyncFunctionStateful2 = addStateToNamedFunction(asyncFunction);

asyncFunctionStateful();
asyncFunctionStateful2();

or create a function factory with closures

function createRequestFunction(url: string) {
  return function request() {
    return fetch(url)
  }
}

const getUsers = addStateToNamedFunction(createRequestFunction('/api/users'));
const getData = addStateToNamedFunction(createRequestFunction('/api/data'));

// getUsers.name === getData.name === 'request'
// so better set name explicitly

But these cases are rare in the real development.