3

i am using laravel-echo to create and use websocket in my react-app. its easy to use laravel-echo in a page. but when need to use in several pages, it make several channel and subscribe several time. how to make a single channel and join ones in several pages ? with props or something ...

i try via props like below but there was some error:

parent Component:

import Echo from 'laravel-echo';

const token = window.localStorage.getItem('access_token');


const options = {
    broadcaster: 'pusher',
    key: '7890165486',
    wsHost: '45.149.78.4',
    wsPort: 6001,
    disableStats: true,
    authEndpoint: 'http://xxx.xxx.net/broadcasting/auth',
    auth: {
        headers: {
            Authorization: `Bearer ${token}`,
            Accept: 'application/json'
        }
    }
};

const echo = new Echo(options);

Class ParentComponnet extends Component {

componentDidMount() {
    this.EchoJoin();
}

EchoJoin() {
    let ch = echo.join(`chat.${this.props.token}`);
    ch
        .here((user) => {
            console.log('all online use', user);
        })
        .joining((user) => {
            alert(user.id + ' New Join the Channel');
        })
        .leaving((user) => {
            alert(user.id + ' Leave the Channel');
        })
        .listen('MessageSent', (e) => {
            console.log('>>>>>>>>>>>>', e);
        });
}
<ChildComponent ch={this.echo} />
}

and this is child Component code :

    componentDidMount() {
    this.props.ch
        .here((user) => {
            console.log('all online use', user);
        })
        .joining((user) => {
            alert(user.id + ' New Join the Channel');
        })
        .leaving((user) => {
            alert(user.id + ' Leave the Channel');
        })
        .listen('MessageSent', (e) => {
            console.log('>>>>>>>>>>>>', e);
        });

    }

i got this error TypeError: Cannot read property 'here' of undefined

mansour lotfi
  • 524
  • 2
  • 7
  • 22

1 Answers1

2

Yes, in a way you answered your own question. You need a singleton here, so I would initialize the connection in a root container, and then pass down what you need as a prop to each screen you need it in.

Let me know if you need any clarification on that.

EDIT: Looks like your connection is called ch, so you would just need to pass that down to your children as a prop. Assuming that you have your code in one of your high level root components/containers - such as App.js - you would pass it down like such.

<View>
  <SomeChildComponent ch={this.ch} />
</View>

EDIT: You are doing this to render your child component:

<ChildComponent ch={this.echo} />

But it should be this:

<ChildComponent ch={this.ch} />

Doug Watkins
  • 1,387
  • 12
  • 19