Search code examples
javascriptreactjslaravellaravel-echo

Insert Laravel Echo in React


I have the following script working perfectly in the welcome.blade.php:

<script>
            Echo.channel('home')
                .listen('NewPatient',(e) => {console.log(e.patient);
                  })            
</script>

Home is the name of a channel, NewPatient is the name of an event.

How to implement this script in a React component so I can display data in that component precisely ?

Patient Component in react :

import React,{Component} from 'react';
import axios from 'axios';
import Echo from "laravel-echo";
 
class Patient extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            patients : []
        };
    }

      
        componentDidMount() {
            axios.get('api/patients')
            .then(response => {this.setState({patients: response.data})})
            .catch(err => console.log(err));   
        }

        
      
        render() {
          return (
            <ul>
              { this.state.patients.map(patient => <li>{patient.nom}</li>)}
            </ul>
          )
        }
      }

export default Patient;

When I try to paste the script in the ComponentDidMount area, I have errors such as laravel_echo__WEBPACK_IMPORTED_MODULE_2__.default.channel and Can't perform a React state update on an unmounted component


Solution

  • Solved! Added window. next to Echo in my code in the ComponentDidmount

    window.Echo.channel('home')
                    .listen('NewPatient',(e) => {console.log(e.patient);
                      })