This package has been deprecated

Author message:

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

use-cors-state
TypeScript icon, indicating that this package has built-in type declarations

1.1.9 • Public • Published

use-cors-state

Custom hooks for synchronizing state between different components, different windows, and cross-domains.

NPM JavaScript Style Guide Build Status TypeScript

Install

# when use npm
npm install --save use-cors-state

# when use yarn
yarn add use-cors-state

DEMO

https://aiji42.github.io/use-cors-state/

Usage

Example for synchronizing state between different windows (e.g. iframe)

// 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.

API

const [state, setState] = useCorsState(synchronizingKey, options, initialValue)
  • synchronizingKey: string
    • Set the same key between components.
  • options: OptionsType | undefined
    • window: optional (Default value is self window)
      • The window in which the opponent's component exists.
    • domain: optional
      • This value can be used to restrict the domain.
    • See "OptionsType" below for more information.
  • initialValue: any
    • Initial value of the state.

OptionsType

// 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
};

Example

// 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 })

License

MIT © aiji42


This hook is created using create-react-hook.

Readme

Keywords

none

Package Sidebar

Install

npm i use-cors-state

Weekly Downloads

0

Version

1.1.9

License

MIT

Unpacked Size

11.4 kB

Total Files

8

Last publish

Collaborators

  • aiji42