¿Cómo actualizar los datos con reaccionar js, por ejemplo, un usuario escribe un comentario sobre cómo hacer que estos mensajes se muestren a todos los demás usuarios? Usé setState en componentDidUpdate con una condición de parada pero no funciona. Si no hago una condición, funciona correctamente pero con bucle infinito.
componentDidUpdate(prevProps, prevState) { console.log("1" + prevState.changeRepComm.toString()) console.log("2" + this.state.changeRepComm.toString()) if (prevState.changeRepComm !== this.state.changeRepComm ) { if (this.updateTimer) return; this.updateTimer = setTimeout(() => { //lister response comments fetch('/api/ReponseCommentaire/listerReponseCommentaire', { method: "GET", headers: { 'Accept': 'application/json, application/xml, text/plain, text/html, *.*', 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(response => { console.log('Ajouter response:' + JSON.stringify(response)) this.setState({ ...this.state, reponseCommentaires: response }); }) .catch((err) => { console.log('fetch failed => ', err); }) }, 1000);} }
Si busca actualizar cada segundo, puede inicializar un temporizador cuando se monta el componente.
componentDidMount(prevProps, prevState) { if (this.updateTimer) { return; } this.updateTimer = setInterval(() => { fetch('/api/ReponseCommentaire/listerReponseCommentaire', { method: "GET", headers: { 'Accept': 'application/json, application/xml, text/plain, text/html, *.*', 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(response => { this.setState({ ...this.state, reponseCommentaires: response, }); }) .catch((err) => console.log('fetch failed => ', err) ) }, 1000); }