{"id":13623004,"url":"https://github.com/pjchender/react-use-opentok","last_synced_at":"2025-04-15T10:32:14.488Z","repository":{"id":38028062,"uuid":"234492639","full_name":"pjchender/react-use-opentok","owner":"pjchender","description":"React Hook for conveniently use @opentok/client SDK.","archived":true,"fork":false,"pushed_at":"2022-06-11T10:24:14.000Z","size":6646,"stargazers_count":28,"open_issues_count":1,"forks_count":13,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-18T13:26:18.537Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://pjchender.github.io/react-use-opentok/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pjchender.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-01-17T07:13:21.000Z","updated_at":"2024-02-02T02:03:23.000Z","dependencies_parsed_at":"2022-09-18T17:51:14.716Z","dependency_job_id":null,"html_url":"https://github.com/pjchender/react-use-opentok","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjchender%2Freact-use-opentok","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjchender%2Freact-use-opentok/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjchender%2Freact-use-opentok/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pjchender%2Freact-use-opentok/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pjchender","download_url":"https://codeload.github.com/pjchender/react-use-opentok/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249051747,"owners_count":21204880,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T21:01:26.850Z","updated_at":"2025-04-15T10:32:14.191Z","avatar_url":"https://github.com/pjchender.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# react-use-opentok\n\n[![Build status](https://badgen.net/travis/pjchender/react-use-opentok)](https://travis-ci.com/pjchender/react-use-opentok)\n[![version](https://img.shields.io/npm/v/react-use-opentok.svg)](https://www.npmjs.com/package/react-use-opentok)\n[![Coverage Status](https://coveralls.io/repos/github/pjchender/react-use-opentok/badge.svg?branch=master)](https://coveralls.io/github/pjchender/react-use-opentok?branch=master)\n[![license](https://img.shields.io/github/license/pjchender/react-use-opentok.svg)](https://github.com/pjchender/react-use-opentok/blob/master/LICENSE)\n[![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg)](#contributors)\n\nReact Hook for conveniently use @opentok/client SDK.\n\n## Pre-requirement\n\n* Register [Opentok](https://id.tokbox.com/login) to get authentication.\n\n## Demo\n\nSee our demo site: [react-use-opentok](https://pjchender.github.io/react-use-opentok/)\n\n![react-use-opentok](https://i.imgur.com/mpmlkrI.gif)\n\n## Installation\n\nInstall it with npm:\n\n```\nnpm i @opentok/client@2.x react-use-opentok\n```\n\nOr with yarn:\n\n```\nyarn add @opentok/client@2.x react-use-opentok\n```\n\n\u003e NOTE: remember to install the peer dependency of [@opentok/client](https://www.npmjs.com/package/@opentok/client)\n\n## Getting Started\n\n1. Get utilities from `useOpenTok` hook\n2. Fetch `apiKey`, `sessionId`, and `token` from server\n3. Connect to session with `token`\n\n```js\nimport React, { useEffect } from 'react';\nimport useOpenTok from 'react-use-opentok';\n\nconst Component = () =\u003e {\n  // STEP 1: get utilities from useOpenTok;\n  const [opentokProps, opentokMethods] = useOpenTok();\n\n  const {\n    // connection info\n    isSessionInitialized,\n    connectionId,\n    isSessionConnected,\n\n    // connected data\n    session,\n    connections,\n    streams,\n    subscribers,\n    publisher,\n  } = opentokProps;\n\n  const {\n    initSessionAndConnect,\n    disconnectSession,\n    publish,\n    unpublish,\n    subscribe,\n    unsubscribe,\n    sendSignal,\n  } = opentokMethods;\n\n  // STEP 2: Mockup fetching apiKey, sessionId, and token from server\n  useEffect(() =\u003e {\n    fetch('\u003cget credentials from server\u003e').then(\n      ({ apiKey, sessionId, token }) =\u003e {\n        initSessionAndConnect({\n          apiKey,\n          sessionId,\n          token,\n        });\n      }\n    );\n  }, [initSessionAndConnect]);\n\n  return \u003cdiv\u003e...\u003c/div\u003e;\n};\n\nexport default Component;\n```\n\n## Guide\n\n### Get all utilities from useOpenTok Hook\n\nYou can get all utilities from `useOpenTok` hook.\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\n\nconst {\n  // connection info\n  isSessionInitialized,\n  connectionId,\n  isSessionConnected,\n\n  // connected data\n  session,\n  connections,\n  streams,\n  subscribers,\n  publisher,\n} = opentokProps;\n\nconst {\n  initSessionAndConnect,\n  disconnectSession,\n  publish,\n  unpublish,\n  subscribe,\n  unsubscribe,\n  sendSignal,\n} = opentokMethods;\n```\n\n### Connect and disconnect to session\n\nBefore starting use openTok session object, remember to initialize session with `apiKey` and `sessionId` by `initSessionAndConnect` method:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { initSessionAndConnect } = opentokMethods;\n\n// apiKey, sessionId, and token could get from your server or tokbox dashboard\ninitSessionAndConnect({\n  apiKey,\n  sessionId,\n  token,\n});\n```\nThis methods will first initialize the session object, and continue connected to the session.\n\nAfter session initialized, the value of `isSessionInitialized` will be `true.\n\nAfter connect to session, you can get the `session`, `connectionId` , `isSessionConnected`, and `connections` properties from `opentokProps`:\n\n- `session`: a session object from [`OT.initSession()`](https://tokbox.com/developer/sdks/js/reference/OT.html#initSession)\n- `connectionId`: your own connectionId\n- `isSessionConnected`: whether you are connected to the session\n- `connections`: all connections in the session\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { session, connectionId, isSessionConnected, connections } = opentokProps;\n```\n\nBy `disconnectSession`, you can disconnect from the session:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { disconnectSession } = opentokMethods;\n\ndisconnectSession();\n```\n\n\u003e If you want to control the process of session initialization and connect to session on your own, check the method `initSession({ apiKey, sessionId, sessionOptions })` and `connectSession({token, sessionToConnect })`.\n\n### Publish and unpublished stream to the session\n\nYou can publish stream from camera or screen to session through the `publish` method.\n\n- `name`: should be unique every time you invoke publish method which is for `unpublish` stream later.\n- `element`: should be a DOM element or the `id` attribute of the existing DOM element.\n- `options`: (optional) other optional properties which will pass into [OT.initPublisher](https://tokbox.com/developer/sdks/js/reference/OT.html#initPublisher).\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { publish } = opentokMethods;\n\n// publish stream from the camera\npublish({\n  name: 'camera',\n  element: 'camera',\n});\n\n// publish stream from screen sharing\npublish({\n  name: 'screen',\n  element: 'screen',\n  options: {\n    insertMode: 'append',\n    width: '100%',\n    height: '100%',\n    videoSource: 'screen',\n  },\n});\n\n// publish support Promise way to catch errors\npublish({\n  name: 'camera',\n  element: 'camera',\n}).catch((ex) =\u003e {\n  console.log(ex);\n});\n```\n\nAccording to the `name` you publish, you could use the same name to unpublish it:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { unpublish } = opentokMethods;\n\n// unpublish stream from the name 'camera'\nunpublish({ name: 'camera' }\n```\n\n### Subscribe and Unsubscribe\n\nYou can get all streams in the session through `streams` property in `opentokProps`. After finding the stream for subscribing, use the `subscribe` method to subscribe to the stream:\n\n- `stream`: the Stream Object wanted to subscribe\n- `element`: should be a DOM element or the `id` attribute of the existing DOM element.\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { streams } = opentokProps;\nconst { subscribe } = opentokMethods;\n\nconst streamToSubscribe = streams[0];\nsubscribe({ stream: streamToSubscribe, element: 'subscriber' });\n```\n\nFor each stream be subscribed, a [subscriber object](https://tokbox.com/developer/sdks/js/reference/Session.html#subscribe) will be created and save as `subscribers` in `opentokProps`:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { streams, subscribers } = opentokProps;\n```\n\nYou can stop subscribing the stream with `unsubscribe` method:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { unsubscribe } = opentokMethods;\n\nconst streamToUnsubscribe = streams[0];\nunsubscribe({ stream: streamToUnsubscribe });\n```\n\n### Send signal\n\nYou can send signal in session with `sendSignal` method:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { sendSignal } = opentokMethods;\n\nsendSignal({\n  type: 'foo',\n  data: 'bar',\n});\n```\n\n### Register session events\n\nYou could register all valid [session events](https://tokbox.com/developer/sdks/js/reference/Session.html#events) on `session` object. Take registering signal event, as an example,  use the `session` object in `opentokProps`, register the session event with `on`, and unregister the event with `off`:\n\n```js\nconst [opentokProps, opentokMethods] = useOpenTok();\nconst { session } = opentokProps;\n\nconst handleSignal = useCallback(e =\u003e {\n  console.log('handleSignal', e);\n}, []);\n\nuseEffect(() =\u003e {\n  if (!isSessionConnected) {\n    return;\n  }\n\n  session.on('signal', handleSignal);\n  return () =\u003e {\n    session.off('signal', handleSignal);\n  };\n}, [handleSignal, isSessionConnected, session]);\n```\n\n\u003e NOTICE: for `sessionDisconnected` event, you can you `session.once('sessionDisconnected', \u003ceventHandler\u003e)`\n\n### (Optional) Preview Solution\n\nYou may want to split `OT.initPublisher` and `session.publish` and invoke it in different stage. To solve the requirement you can use `initPublisher` and `publishPublisher` instead. If you need to cancel preview you can use `removePublisher` as well.\n\nNOTE:\n\n* `initPublisher` - Same with `OT.initPublisher` but support state which means you can access `publisher`.\n* `removePublisher` - The method can only remove `publisher` without publish. Once you publish the `publisher` you should use `unpublish` instead.\n* `publishPublisher` - Publish for `initPublisher`.\n\n`initPublisher` + `publishPublisher` = `publish`\n\nFor example:\n\n```js\nconst Component = () =\u003e {\n  const [opentokProps, opentokMethods] = useOpenTok();\n\n  const {\n    initPublisher,\n    publishPublisher,\n    removePublisher,\n  } = opentokMethods;\n\n  // ...\n\n  const onInitPublisher = () =\u003e {\n    initPublisher({\n      name: 'guest',\n      element: 'guest',\n      options: {\n        insertMode: 'append',\n        width: '480px',\n        height: '360px',\n      },\n    });\n  };\n  const onPublishPublisher = () =\u003e {\n    publishPublisher({\n      name: 'guest',\n    });\n  };\n  const onRemovePublisher = () =\u003e {\n    removePublisher({\n      name: 'guest',\n    });\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv id=\"guest\"\u003e\u003c/div\u003e\n      \u003cdiv\u003e\n        \u003cbutton onClick={onInitPublisher}\u003eInit Publisher without publish\u003c/button\u003e\n        \u003cbutton onClick={onRemovePublisher}\u003eRemove Publisher before publish\u003c/button\u003e\n        \u003cbutton onClick={onPublishPublisher}\u003ePublish Publisher\u003c/button\u003e\n      \u003c/div\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## Development\n\n### for react-use-opentok package\n\n```sh\n$ npm install\n$ npm start         # rollup will watch the files change\n$ npm build         # rollup will build the package\n$ npm test\n```\n\n### for example site\n\n```sh\n$ cd site\n$ npm install\n$ npm start         # start gatsby develop server\n```\n\n## Contributors\n\nThanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)):\n\u003c!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://andyyou.github.io/\"\u003e\u003cimg src=\"https://avatars0.githubusercontent.com/u/665690?v=4\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eandyyou\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pjchender/react-use-opentok/commits?author=andyyou\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"#design-andyyou\" title=\"Design\"\u003e🎨\u003c/a\u003e \u003ca href=\"#example-andyyou\" title=\"Examples\"\u003e💡\u003c/a\u003e \u003ca href=\"#maintenance-andyyou\" title=\"Maintenance\"\u003e🚧\u003c/a\u003e \u003ca href=\"#ideas-andyyou\" title=\"Ideas, Planning, \u0026 Feedback\"\u003e🤔\u003c/a\u003e \u003ca href=\"https://github.com/pjchender/react-use-opentok/pulls?q=is%3Apr+reviewed-by%3Aandyyou\" title=\"Reviewed Pull Requests\"\u003e👀\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"http://pjchender.blogspot.com\"\u003e\u003cimg src=\"https://avatars1.githubusercontent.com/u/13399740?v=4\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003ePJCHENder\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pjchender/react-use-opentok/commits?author=pjchender\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/pjchender/react-use-opentok/commits?author=pjchender\" title=\"Documentation\"\u003e📖\u003c/a\u003e \u003ca href=\"https://github.com/pjchender/react-use-opentok/commits?author=pjchender\" title=\"Tests\"\u003e⚠️\u003c/a\u003e \u003ca href=\"#example-pjchender\" title=\"Examples\"\u003e💡\u003c/a\u003e \u003ca href=\"#maintenance-pjchender\" title=\"Maintenance\"\u003e🚧\u003c/a\u003e \u003ca href=\"https://github.com/pjchender/react-use-opentok/pulls?q=is%3Apr+reviewed-by%3Apjchender\" title=\"Reviewed Pull Requests\"\u003e👀\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/Mwjrink\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/29183162?v=4\" width=\"100px;\" alt=\"\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eMaximillian Rink\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/pjchender/react-use-opentok/commits?author=Mwjrink\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\u003c!-- markdownlint-enable --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\nThis project follows the [all-contributors](https://allcontributors.org/) specification. Contributions of any kind welcome!\n\n## LICENSE\n\n[MIT](https://github.com/pjchender/react-use-opentok/blob/master/LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpjchender%2Freact-use-opentok","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpjchender%2Freact-use-opentok","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpjchender%2Freact-use-opentok/lists"}