Open simonbuchan opened 6 years ago
@simonbuchan You might find useful the react-with-observable
package I created: https://github.com/mmiszy/react-with-observable
It allows you to use Observables declaratively in React. It's compatible with React 16.3+ and it uses create-subscription
under the hood. It includes TypeScript definitions and has 100% integration tests coverage.
That actually looks very good, barring minor quibbles like the extra wrapping component / defaulting to ''
(rather than setting the initial state to null
)!
I ended up building a component from scratch (though with an API that assumes map
) based on the gist mentioned on the note in that last post I linked / create-subscription
's readme, so it should be behaving effectively the same. Maybe it will be useful to someone?
Subscribe.tsx
Thanks for the tips @simonbuchan, I was considering using that gist but decided to go simpler route in the end and I just used create-subscription
. It's maintained by Facebook and I hope it'll be updated in case any breaking-changes are introduced in React 17 — so I don't have to worry about it.
React 16.0 relaxed
render()
return types to anything renderable (whichprop-types
and@types/react
call a "node"), so you should return the observer output as-is, and not wrap in<span/>
(which can break layouts). See https://reactjs.org/blog/2017/09/26/react-v16.0.htmlReact 16.3 has deprecated
componentWill*
methods (except forcomponentWillUnmount
), and will warn if they are used. See https://reactjs.org/blog/2018/03/29/react-v-16-3.html. In my version of this, I simply used theDid
versions instead, which seems to be mostly fine, but in the new async rendering mode, these might run some time after render, which could be a problem for synchronous observable outputs. Further,WillUpdate
may run multiple times before an update, though it's not actually described why. Thecreate-subscription
package the react blog mentions here might be a relevant reference (perhaps this library would work as a wrapper on it?)