Coder Social home page Coder Social logo

betomorrow / micro-observables Goto Github PK

View Code? Open in Web Editor NEW
104.0 104.0 8.0 1.92 MB

A simple Observable library that can be used for easy state management in React applications.

License: MIT License

TypeScript 99.23% JavaScript 0.77%
hooks mobx observable react redux state-management

micro-observables's People

Contributors

andreabreu-me avatar dependabot[bot] avatar jesse-holden avatar krishemenway avatar simontreny avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

micro-observables's Issues

react batching broken

from app code:

import "micro-observables/batchingForReactDom"

message:

ERROR in ./node_modules/micro-observables/batchingForReactDom.js
Module not found: Error: Can't resolve './lib' in '/home/peter/Dev/.../node_modules/micro-observables'
@ ./node_modules/micro-observables/batchingForReactDom.js 2:0-16


perhaps this feature is incomplete?

Including a dev tool

Thank you for this great library.
It helps me easily separating my business logic from my React code.

I use a logger to display the state of my micro observables and it is a bit of a mess.

I read in a previous issue that your team is working on version 2.x for releasing a dev tool (similar to the Redux dev tool interface I guess)

Is the work about it still in progress? It would be great to have some updates

Cheers :)

using micro-observables library without react

I'm becoming quite fond of micro-observables and I'd like to use it in a library I'm writing that is not React based. I see 'react' is a peerDependency which will work fine but of course npm/yarn will complain of an unmet peerDependency.

The only react requirement if the hooks within https://github.com/BeTomorrow/micro-observables/blob/master/src/hooks.ts#L1, a thought would be to package this as a separate library just for the hook? or I believe making 'react' an optionalDependency might work as well.

avoid updates when value did not change (with custom equality function)

I have a graph of observables, that originate from a rapidly changing one (a redux store that we want to migrate away from).

I want derived observables to only propagate updates if their value actually changed.
I want to use a custom equality function to determine if something changed (e.g. structual equality over reference equality).

I know that I can compare current and last value inside subscribe, but most of my observables are not directly subscribed, but are used as inputs to other observables, which are unnessecarily recomputed.

I propose an additional, optional parameter isEqual(next: T, current: T): boolean, to .select() and .compute(), after the lambda function, where you can pass in an equality function that is evaluated on every update after the initialitation of the observable. If it returns true, the observable is not updated with the computed value.

import { isEqual } from "lodash"

const signalSpeed: Observable<Speed> = reduxStore.select(store => ({
  pxPerMm: store.config?.getSettings("pxPerMm") ?? 0,
  mmPerSec: store.config?.getSettings("signalSpeed") ?? 0,
}), isEqual)

middleware

I think it'd be great to have a middleware adapter interface for getters/setters and maybe other stuff. It would be useful to attach things like a logger during debugging situations to find out the code path of code being set. I feel it would be pretty easy to add too

btw (as an aside point), mobx6 came out today and its certainly cleaner then mobx4/5, but I still feel the micro footprint of micro-observables and smaller surface api makes for a better experience. However mobx is definitely more battle tested and has things like middleware for logging. My main thing with micro-observables is ensuring im not re-rendering more often than I want, and also to ensure consistency of the data as its being updated, perhaps this is why mobx encourages to make updates within an action() call. Maybe micro-observables should also have some explicit call to make a batch'd update in a single tick instead of having multiple state updates go across render ticks and make for unnecessary re-renders.

another interesting fact.. micro-observables/src/* is 328 lines of code, and mobx/src/* is 5312 lines of code.. 93% smaller which is a pretty awesome achievement, but I still think more can be done to micro-observables to make it better while still keeping the surface api as small as possible and keeping spirit of explicitness

(UPDATE: just found in the docs Observable.batch(block: () => void) for batch updating, nice)

Add ES module distribution

For use with modern bundling tools like Vite and Snowpack. At the moment, Vite tries to optimize the library as a CommonJS module with a single default export, then errors with this at runtime:

Uncaught SyntaxError: The requested module '/@modules/micro-observables.js' does not provide an export named 'observable'

Adding an ES module distribution would fix this. I'm also open to adding this myself

React hook useObservable and SSR warnings

When useObservable is used in a Server Side rendering context, it raises a React warning:

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-
hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for
common fixes.

To avoid this, the solution described here could be easily applied: https://medium.com/@alexandereardon/uselayouteffect-and-ssr-192986cdcf7a

So for example, the code might look like this:

const useSsrCompatibleLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;

export function useObservable<T>(observable: Observable<T>): T {
  const [, forceRender] = useState({});
  const val = observable.get();

  useSsrCompatibleLayoutEffect(() => {
    return observable.subscribe(() => forceRender({}));
  }, [observable]);

  return val;
}

useObservable forceRender race condition

I've encountered a very obscure race condition when using multiple useObservable hooks across a variety of components.

The gist of it is when two different React components are observing multiple observables in the same store, a change in one observable will trigger a forceRender, which will cause the useEffect() effect function to be called, and when it returns it will call the unsubscribe method of the onChange method, and prevents the change notification to be delivered (as its no longer listening in between the change), https://github.com/BeTomorrow/micro-observables/blob/master/src/hooks.ts#L8. There is a timing issue where the onChange unsubscribers will be called by the effect's return function, removing the listener of an observable that in-turn will also be updated a set call from the store.

The result is one component updates, and the other does not as it never receives the onChange listener call and never calls its own forceRender. This happens especially with multiple shared observables across multiple components. I've experienced this in my own application that uses stores declaratively (like a spreadsheet).

One solution which works is to defer the unsubscribe calls:

export function useObservable<T>(observable: Observable<T>): T {
	const [, forceRender] = useState({});

	useEffect(() => {
		const unsubscribe = observable.onChange(() => forceRender({}));
		return () => {
			setTimeout(() => unsubscribe(), 150);
		}
	}, [observable]);

	return observable.get();
}

Using a timeout is certainly not ideal here but it does solve the issue. Its possible there is a circular dependency between observables and components, but this case should be considered. Please lmk if you have other ideas.

Individual observables vs object

Hi there,

I'm really enjoying the simplicity of this library and pattern. It reminds me of mobx but much simpler/lighter.

I'm wondering if you have an example in the wild using this library however as I'm trying to decide between the right patterns that offer nice syntax sugar, readability, succinctness and performance.

One question is, in a TodoService (which I prefer to call TodoStore), I would usually have a number of fields inside of a store, and I'm trying to decide if I should make a single observable state object, or break it into multiple observable values.

class SomeStore {
  state = observable({
    enabled: false,
    name: '',
    age: 30
  })
}

or.. separate..

class SomeStore {
  enabled = observable<boolean>(false)
  name = observable<string>('')
  age = observable<number>(30)
}

I will admit, I prefer the second approach with individual observables, but, I can't manage to come up with a new useObservable or a new useStore hook pattern to make it easy to consume the entirety of the store without having to relist each individual observable.

the other part to this pattern is considering serialization which is useful for cases when an app needs SSR.

thank you

Observable.proxy idea

I have a scenario where I have an object that I'd like to turn into a micro-observable so I can use with the rest of observable state in the project.

I initially thought I could use Observable.compute(), but of course this is to compute only other structures already represented as an Observable value from micro-observables.

How about the idea of adding a Observable.proxy or Observable.wrap method, which could use the Proxy API to listen for changes in these situations?

Handling nested observable that is possibly undefined

Hello,
This is not strictly a bug it's more of an edge case that i'm not sure how to handle or the best pattern to make it work.

Say I have an item that has a nested observable for quantitySelected. Just doing:

const selectedItem = useObservable(itemStore.selectedItem)
const selectedItemValue = useObservable(selectedItem.quantitySelected)

Will cause it to break when selectedItem is undefined.

I can fix this by having a conditional hook but, this will cause other issues due to this being an anti-pattern.

const selectedItem = useObservable(itemStore.selectedItem)
const selectedItemValue = selectedItem ? useObservable(selectedItem.quantitySelected) : 0

Would appreciate any help on this.

Thank you

Add react-dom as an optional dependency

Currenty batchingForReactDom.js references react-dom even through react-dom is not referenced in the project package.json file.

It seems to cause an issue with recent versions of Yarn.

Would it be possible to react-dom to the optional dependencies of the package.json file? And I guess it should be the same with react-native.

Here is the full error from Yarn:

errors: [
  {
    detail: undefined,
    id: '',
    location: {
      column: 25,
      file: '../.yarn/__virtual__/micro-observables-virtual-7722fe8c8c/0/cache/micro-observables-npm-1.7.2-8e88bfdb52-15dd9eadc5.zip/node_modules/micro-observables/batchingForRea
ctDom.js',
      length: 11,
      line: 1,
      lineText: 'const ReactDOM = require("react-dom");',
      namespace: '',
      suggestion: ''
    },
    notes: [
      {
        location: {
          column: 33,
          file: '../.pnp.cjs',
          length: 343,
          line: 9047,
          lineText: '          "packageDependencies": [\\',
          namespace: '',
          suggestion: ''
        },
        text: `The Yarn Plug'n'Play manifest forbids importing "react-dom" here because it's not listed as a dependency of this package:`
      },
      {
        location: null,
        text: 'You can mark the path "react-dom" as external to exclude it from the bundle, which will remove this error. You can also surround this "require" call with a try/cat
ch block to handle this failure at run-time instead of bundle-time.'
      }
    ],
    pluginName: '',
    text: 'Could not resolve "react-dom"'
  }
]

"Cannot find module './lib'" ReactDOM Batching

Hello,

Thanks for creating and maintaining this package! I've come across an issue when trying to implement ReactDOM Batching in version 1.5.0-rc4.

Uncaught Error: Cannot find module './lib'
    at webpackMissingModule (batchingForReactDom.js:2)
    at Object../node_modules/micro-observables/batchingForReactDom.js (batchingForReactDom.js:2)
    at __webpack_require__ (bootstrap:832)
    at fn (bootstrap:129)
    at Module../src/index.tsx (index.tsx:2)
    at __webpack_require__ (bootstrap:832)
    at fn (bootstrap:129)
    at Object.0 (debug-relayer.ts:13)
    at __webpack_require__ (bootstrap:832)
    at bootstrap:970

Sure enough when I look at the installed module there is no such ./lib folder in the directory. Please advise on what I may be missing here.

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.