dnamsons / rails-hooks

Rails javascript APIs turned into Hooks for use in functional React components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rails hooks

Version

Installation

with npm

npm install rails-hooks

with yarn

yarn add rails-hooks

API

useCable

Requires for CableProvider to be set somewhere above the component where useCable will be used.

import React from 'react'
import { CableProvider } from 'rails-hooks'
import { createConsumer } = '@rails/actioncable'

const App = () => {
  const consumer = createConsumer('optional-url.com')

  return(
    <CableProvider consumer={consumer}>
      ...
    </CableProvider>
  )
}

Then useCable can be used like this:

import { useCable } from 'rails-hooks'

const [messages, setMessages] = useState([])

const chatChannel = useCable(
  { channel: 'ChatChannel', room: 'Best room' },
  {
    received(data) {
      setMessages(prevMessages => [...prevMessages, data])
    },
  }
)

chatChannel.send({ sent_by: 'Paul', body: 'This is a cool chat app.' })

About

Rails javascript APIs turned into Hooks for use in functional React components

License:MIT License


Languages

Language:TypeScript 100.0%