with npm
npm install rails-hooks
with yarn
yarn add rails-hooks
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.' })