Tengo una aplicación Rails + React (proyectos separados) y he creado un websocket ActionCable para enviar mensajes simples desde el backend al frontend. El websocket funciona, puedo ver todo en la interfaz, pero no puedo ver las actualizaciones en tiempo real, solo después de actualizar. No sé cómo implementar la actualización en tiempo real.
Aquí está mi código:
import PropTypes from 'prop-types' import { Switch, Route } from 'react-router-dom' import actionCable from 'actioncable' import { DUMMY_QUERY } from 'Queries' // app/javascript/packs/messages.js import React, { useState, useEffect } from 'react' import ReactDOM from 'react-dom' import MessagesChannel from './channels/messages_channel' function useForceUpdate(){ const [value, setValue] = useState(0); // integer state return () => setValue(value => value + 1); // update the state to force render } function Dummy() { const [messages, setMessages] = useState([]) const [message, setMessage] = useState('') const [rerender, setRerender] = useState(false); useEffect(() => { MessagesChannel.received = (data) => { setMessages(data.messages) console.log(data) } }, []) /*const handleSubmit = async (e) => { e.preventDefault() // Add the X-CSRF-TOKEN token so rails accepts the request await fetch('http://localhost:3000/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message }), }) setMessage('') }*/ return ( <div> <ul> {messages.map((message) => ( <li key={message.id}>{message.content}</li> ))} </ul> </div> ) } export default DummyEl cable activo también tiene un componente frontal. Nunca lo he usado junto con reaccionar, pero con js puro se ve así:
Importe la lib (consumer.js):
import { createConsumer } from "@rails/actioncable" export default createConsumer()Cargue todos los canales definidos en su repositorio (index.js):
const channels = require.context('.', true, /_channel\.js$/) channels.keys().forEach(channels)Defina un archivo js para cada canal (message_channel.js):
import consumer from "./consumer" consumer.subscriptions.create("MessagesChannel", { connected() { // Called when the subscription is ready for use on the server }, disconnected() { // Called when the subscription has been terminated by the server }, received(data) { // Called when there's incoming data on the websocket for this channel console.log(data) } });Editar: Acabo de descubrir que también hay un paquete npm para los componentes de interfaz .