Giter VIP home page Giter VIP logo

use-phoenix-channel's Introduction

use-phoenix-channel

A React hook that allows for responding to and broadcasting messages over Phoenix channels.

See the "Improving UX with Phoenix Channels & React Hooks" Blogpost for an example use case.

npm install use-phoenix-channel
// or
yarn add use-phoenix-channel

There are two main pieces to the libray, the SocketProvider Component and the useChannel hook.

SocketProvider Component

To be used once at a high level in the component tree similar to Redux Provider:

import React from 'react'
import { SocketProvider } from 'use-phoenix-channel'

const Root = (props) => {
 return (
   <SocketProvider wsUrl='localhost:4000/socket', options={{ token }}>
     <App />
   </SocketProvider>
  )
}

export default Root

useChannel Hook

import React from 'react'
import { useChannel } from 'use-phoenix-channel'

const MyComponent = () => {
  const [state, broadcast] = useChannel(channelName, reducer, initialState)
  // ...
}

The useChannel hook gives a component access to state that will update in real time in response to messages broadcast over a channel. It also gives a component access to a function to broadcast messages over the specified channel.

It should be passed the name of the channel, a reducer function defining the messages to respond to and any initial state.

Responding to Messages

import React from 'react'
import { useChannel } from 'use-phoenix-channel'

const channelName = 'counter:example'
const countReducer = (state, {event, payload}) => {
  // the second argument is the message sent over the channel
  // it will contain an event key and a payload key
  switch(event) {
    case 'increment':
      return state + payload.amount
    case 'decrement':
      return state - payload.amount
  }
}
const initialState = 0

const MyComponent = (props) => {
  const [{ count }, broadcast] = useChannel(channelName, countReducer, initialState)

  return (
    <div>
      <h1>{`The value below will update in realtime as the count is changed by other subscribers to the {channelName} channel`}</h1>
      { count }
    </div>
  )
}

Broadcasting Messages

The broadcast function returned by the hook can be invoked to push messages onto the channel. It should be passed the event name and a payload.

import React from 'react'
import { useChannel } from 'use-phoenix-channel'

const MyComponent = (props) => {
  const [state, broadcast] = useChannel(channelName, reducer, initialState)

  return (
    <div>
      <button onClick={() => broadcast("increment", {amount: props.amount}) }>
        {`Increment by ${props.amount}`}
      <button />
      <button onClick={() => broadcast("decrement", {amount: props.amount}) }>
        {`Decrement by ${props.amount}`}
      <button />
    </div>
  )
}

use-phoenix-channel's People

Contributors

alexgriff avatar

Stargazers

Chola Chilufya avatar Amegbleame Komlanvi avatar Aaron Cruz avatar  avatar Ajay avatar minhlq avatar Camilo avatar Simon Escobar Benitez avatar Radek Szymczyszyn avatar Sergio Mattei avatar Jamal Jean - Tobias  avatar Ethan Sherbondy avatar Yasin ATEŞ avatar Dubois Hugues avatar Jack Kennedy avatar Conor Sinclair avatar Cody Russell avatar Paul Bricout avatar Lachezar Yankov avatar Renato Ceolin avatar Vitor Klein avatar Guilherme Guatura avatar Guilherme Mota avatar Michael Alaev avatar Laura Beatris avatar Filipe Herculano avatar Luis Sebastián Huerta avatar Bruno Macabeus avatar Alex Vallejo avatar Tai An Su avatar Mark Perkins avatar Michael Rode avatar Henry S avatar  avatar  avatar Hew avatar chaichai avatar Patrick G avatar Ben Smith avatar Shawn O'Neill avatar Chris Gaudreau avatar Nick West 韋羲 avatar Ben Munat avatar Erik Storm avatar

Watchers

Ben Munat avatar James Cloos avatar Jason Shen avatar  avatar  avatar

use-phoenix-channel's Issues

How do I dispatch to the reducer?

I have a case where I have a local state that I want to keep in sync with the state in useChannel. Normally if I was working with useReducer I would dispatch any changes. Is there a way to do that here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.