useRefract
Used to create a custom hook.
Packages
useRefract is provided by our React packages - refract-*. It is only available for versions of React supporting hooks (React 16.7.0-alpha.0 and above).
Signature
const useRefract = useRefract(aperture, data, {
handler,
errorHandler
})Arguments
aperture(function): a function which observes data sources within your app, passes this data through any necessary logic flows, and outputs a stream ofeffectvalues in response.Signature:
(component, initialData) => { return effectStream }.The
initialDatapassed to the hook (second argument).The
componentis an object which lets you observe: see Observing React. Theobservemethod allows you to observedatapassed to your hook.Within the body of the function, you observe the event source you choose, pipe the events through your stream library of choice, and return a single stream of effects.
data(object): an object of data (state, props, context) passed to your hook.handler(function): a optional function which causes side-effects in response toeffectvalues.Signature:
(initialData) => (effect) => { /* handle effect here */ }The
initialDatapassed to the hook (second argument).The
effectis each value emitted by youraperture.Within the body of the function, you cause any side-effect you wish.
errorHandler(function): an optional function for catching any unexpected errors thrown within youraperture. Typically used for logging errors.Signature:
(initialData) => (error) => { /* handle error here */ }The
initialDatapassed to the hook (second argument).The
erroris each value emitted by youraperture.Within the body of the function, you cause any side-effect you wish.
Returns
componentData (any): Refract hooks have a special built-in effect to push data to your component. Effects emitted by your aperture and wrapped with toRender will be returned by your hook.
import { toRender } from 'refract-rxjs'Example
import { useRefract } from 'refract-rxjs'
const handler = initialData => effect => {
switch (effect.type) {
case 'localstorage':
localStorage.setItem(effect.name, effect.value)
return
}
}
const aperture = (component, initialData) => {
return component.observe('username').pipe(
debounceTime(2000),
map(username => ({
type: 'localstorage',
name: 'username',
value: username
}))
)
}
const BaseComponent = () => {
const [ username, setUsername ] = useState()
useRefract(aperture, { username }, { handler })
return <input value={username} onChange={evt => setUsername(evt.target.value)} />
)Tips
Take a look at our recipe for dependency injection into your Refract components.
Last updated