Custom hooks for synchronizing state between different components, different windows, and cross-domains.
MIT License
Custom hooks for synchronizing state between different components, different windows, and cross-domains.
# when use npm
npm install --save use-cors-state
# when use yarn
yarn add use-cors-state
https://aiji42.github.io/use-cors-state/
// a componet in parent window
import React from 'react'
import { useCorsState } from 'use-cors-state'
const ExampleComponentParentWindow = ({ targetIframe }) => {
const [state, setState] = useCorsState('example', { window: targetIframe.contentWindow }, '')
return (
<div>
<input type="text" value={state} onChange={(e) => setState(e.target.value)} />
</div>
)
}
// a componet in child window
import React from 'react'
import { useCorsState } from 'use-cors-state'
const ExampleComponentChildWindow = () => {
const [state, setState] = useCorsState('example', { window: window.parent }, '')
return (
<div>
<p>inputted in parent: {state}</p>
</div>
)
}
When setState is executed, the state is synchronized between both windows.
Synchronization is possible from both sides, not only from parent to child, but also from child to parent.
const [state, setState] = useCorsState(synchronizingKey, options, initialValue)
string
OptionsType | undefined
any
// Server
// Loosely based on: https://github.com/krakenjs/post-robot/blob/master/src/public/server.js
type OptionsType = {
handler?: (err: any) => void,
errorHandler?: ({ source: Window, origin: string, data: Object }) => (void | any | ZalgoPromise<any>),
window?: Window,
name?: string,
domain?: (string | RegExp | Array<string>),
once?: boolean,
errorOnClose?: boolean
};
// synchronize to window of a iframe
useCorsState('exampleKey', { window: iframe.contentWindow }, { userId: 1002 })
// specific the domain of the parent window.
useCorsState('exampleKey', { window: window.parent, domain: 'http://example.com' }, { userId: 1002 })
MIT © aiji42
This hook is created using create-react-hook.