{"id":26964425,"url":"https://github.com/nicklayb/phoenix-react","last_synced_at":"2025-10-18T22:37:49.113Z","repository":{"id":57323008,"uuid":"143555062","full_name":"nicklayb/phoenix-react","owner":"nicklayb","description":"A React context provider to handle Phoenix channels websocket events","archived":false,"fork":false,"pushed_at":"2019-02-03T15:51:21.000Z","size":188,"stargazers_count":5,"open_issues_count":0,"forks_count":2,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-03-15T20:48:28.483Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/nicklayb.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2018-08-04T19:03:15.000Z","updated_at":"2021-07-07T19:11:15.000Z","dependencies_parsed_at":"2022-09-11T16:32:36.510Z","dependency_job_id":null,"html_url":"https://github.com/nicklayb/phoenix-react","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fphoenix-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fphoenix-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fphoenix-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicklayb%2Fphoenix-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nicklayb","download_url":"https://codeload.github.com/nicklayb/phoenix-react/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246948008,"owners_count":20859362,"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":"2025-04-03T06:31:25.868Z","updated_at":"2025-10-18T22:37:49.032Z","avatar_url":"https://github.com/nicklayb.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# phoenix-react\n\nThe package offers state support for [Phoenix Channels](https://hexdocs.pm/phoenix/channels.html) using the [React's Context API](https://reactjs.org/docs/context.html). The only external dependency is [Phoenix js](https://hexdocs.pm/phoenix/js/).\n\nIt provides :\n- Central state for your events\n- Simple channel and events registration\n- HOC for easy coupling with the Provider\n\n## Running the example\n\n- Clone the repository\n\n```\ngit clone https://github.com/nicklayb/phoenix-react\n```\n\n- Install npm packages\n\n```\nnpm install\n//  or\nyarn install\n```\n\n- Run development environment\n\n```\nnpm run dev\n```\n\n## Getting started\n\n### Install the dependency\n\nUsing npm\n```sh\nnpm install --save phoenix-react\n```\n\nUsing yarn\n```sh\nyarn add phoenix-react\n```\n\n### Setting up the context Provider\n\n```jsx\nimport React from 'react'\nimport ChannelProvider from 'phoenix-react'\nimport channels from './channels'\n\n//  Refers the initial state you want\nconst state = {\n  messages: [],\n}\n\n//  Refering to the `opts` parameter for Pheonix.Socket instanciation\nconst params = {\n  params: {\n    token: localStorage.token,\n  },\n}\n\nexport default () =\u003e (\n  \u003cChannelProvider\n    url=\"ws://localhost:4000/socket\"\n    channels={channels}\n    state={state}\n    params={params}\n  \u003e\n    \u003cApp /\u003e\n  \u003c/ChannelProvider\u003e\n)\n```\n\n#### Writings channels handler\n\nThis `channels` prop of the provider is an array of channel you create with the `createChannel` helper. The first parameter is the topic to subscribe and the second one is a callback that will setup the socket.\n\nWithin the callback function, you receive the `channel` as first paramter and the provider value which has `mutate`, `fire`, `state` and `getters`props. I highly recommend creating mutats\n\n```js\nimport { createChannel } from 'phoenix-react'\n\n//  Messages mutators. These are helpers that will mutate the state withing a payload. Even though these are not required, they are recommended.\nconst messageMutators = {\n  add: (state, message) =\u003e ({\n    ...state,\n    messages: [\n      ...state.messages,\n      message\n    ],\n  }),\n  set: (state, messages) =\u003e ({\n    ...state,\n    messages: messages,\n  }),\n}\n\n//  The message channel, the mutate function performs a state mutation of the provider which will re-render the consumer components.\nconst messageChannel = createChannel('room', (channel, { mutate }) =\u003e {\n\n  //  You can add handlers for different events. This one with add a message to the state when the `new_msg` event is broadcasted by the Phoenix server\n  channel.on('new_msg', ({ body }) =\u003e {\n    mutate(state =\u003e messageMutators.add(state, body.message))\n  })\n\n  //  Don't forget to join the channel. You can also chain `receive(message, body)` to it to handle different server return code. See Phoenix.js documentation for more information\n  channel.join()\n    .receive('ok', ({ body }) =\u003e {\n      mutate(state =\u003e messageMutators.set(state, body.messages))\n    })\n\n  //  Return that channels to it can be stored into the provider\n  return channel\n})\n\nexport default [\n  messageChannel,\n]\n```\n\n### Coupling components to the provider\n\nTo bind state mutations to components, there is two way. Wither use the Consumer or the HOC. In either way, you will receive the following payload:\n\n- `fire(channel, event, body)`: function that fires an event to the server on the desired channel.\n- `state`: The current state of your provider which **should not** be mutated. Use the mutate function instead.\n- `getters`: The getter object you passed to the provider. These are \"quick access functions\" to your state.\n- `mutate(state =\u003e state)`: function that directly mutates the state.\n- `leave(topice)`: function that leaves the given channel.\n\n#### Using the Consumer\n\nSimply wrap the location where you want to use the provider state by the consumer.\n\n```jsx\nimport React from 'react'\nimport ChannelsProvider from 'phoenix-react'\n\nexport default () =\u003e (\n  \u003cdiv className=\"app\"\u003e\n    \u003cdiv className=\"message-list\"\u003e\n      \u003cul\u003e\n        \u003cChannelsProvider.Consumer\u003e\n          {({ state }) =\u003e state.messages.map(message =\u003e (\n            \u003cli\u003e[{message.author}]: {message.text}\u003c/li\u003e\n          ))}\n        \u003c/ChannelsProvider.Consumer\u003e\n      \u003c/ul\u003e\n    \u003c/div\u003e\n  \u003c/div\u003e\n)\n```\n\n#### Using the High-order component (HOC)\n\nJust wrap the Component while edefault exporting it. The advantage of the HOC is that you can pass a `mapState` function as second parameter to map the only thing want from the payload.\n\n```jsx\nimport React from 'react'\nimport { withChannels } from 'phoenix-react'\n\nconst MessageList = ({ messages }) =\u003e (\n  \u003cul\u003e\n    {messages.map(message =\u003e (\n      \u003cli\u003e[{message.author}]: {message.text}\u003c/li\u003e\n    ))}\n  \u003c/ul\u003e\n)\n\nconst WrappedMessageList = withChannels(MessageList, ({ state }) =\u003e ({\n  messages: state.messages\n}))\n\nexport default () =\u003e (\n  \u003cdiv className=\"app\"\u003e\n    \u003cdiv className=\"message-list\"\u003e\n      \u003cWrappedMessageList /\u003e\n    \u003c/div\u003e\n  \u003c/div\u003e\n)\n```\n\n## API\n\n### `ChannelsProvider`\n\n#### `state`\n\n`object` that contains the initial state of the context\n\n```js\n{\n  messages: [],\n}\n```\n\n#### `getters`\n\n`object` that contains fucntion that receives params and state\n\n```js\n{\n  unread: (_, state) =\u003e state.messages.filter(message =\u003e !message.read),\n}\n```\n\n#### `callbacks`\n\n`object` that has `onSocketError` and `onSocketClose` keys for callbacks on socket events. These events will receive the provider value.\n\n```js\n{\n  onSocketError: (error, provider) =\u003e { /* */ }\n  onSocketClose: (provider) =\u003e { /* */ }\n}\n```\n\n#### `url`\n\n`string` that represents the websocket/longpolling host like `ws://localohst:4000/socket`\n\n#### `params`\n\n`object` that is passed to the socket constructor. There is a nested `params` key that represents the params sent to the websocket server. Refer to the Phoenix js documentation.\n\n```js\n{\n  params: {\n    token: 'Bearer ...',\n  },\n}\n```\n\n#### `channels`\n\n`array` of channel created within the `createChannel` helper.\n\n```js\n[\n  createChannel('room:lobby', (channel, { mutate }) =\u003e {\n    /* setup channel */\n  }),\n  createChannel('room:1', (channel, { mutate }) =\u003e {\n    /* setup channel */\n  }),\n]\n```\n\n#### `timeout`\n\n`number` that represents the timeout duration in milliseconds like `5000`\n\n\n### `withChannels`\n\n#### `Component`\n\nReact component that you want to map the provider value.\n\n```js\nexport default withChannels(Component)\n```\n\nThe component now receives `state`, `fire`, `getters`, `mutate` and `leave`.\n\n#### `mapState`\n\n`function` that receive the provider value and return only what you want to attach to your component\n\n```js\nexport default withChannels(Component, ({ state, fire }) =\u003e ({\n  messages: state.messages,\n  fire,\n}))\n```\nThe component now receives on `messages` and `fire`.\n\n### `createChannel(topic, callback: (channel, providerValue))`\n\n`function` that receives a `topic` string and a `callback`. That callback receives `channel` which is the `socket.channel` instance and the provider value. The callback **must** return the channel and make sure to call `join` before returning.\n\n```js\nconst channel = createChannel('room:lobby', (channel, { mutate }) =\u003e {\n  channel.on('new_msg', ({ message }) = {\n    mutate(state =\u003e {\n      ...state,\n      messages: [\n        ...state,\n        message\n      ],\n    })\n  })\n  channel.join()\n  return channel\n})\n```\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicklayb%2Fphoenix-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnicklayb%2Fphoenix-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicklayb%2Fphoenix-react/lists"}