Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
¿Cómo ver la actualización en tiempo real en React?

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 Dummy
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

El 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 .

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!