user11770089
user11770089

Reputation:

How to set state of component in Signalr connection.on()

I want to get data from server with signalr and update content of React component. Everything is ok. Data is received from the server BUT state of component could not update (undefined).

Here is my code:

import React, { Component } from 'react';
import { ToastComponent } from '@syncfusion/ej2-react-notifications';
import * as signalR from '@aspnet/signalr';


class Notification extends React.Component {

    constructor() {
        super(...arguments);
        this.position = { X: 'Right', Y: 'Top' }
        this.state = { message:null}

    }

    toastCreated() {
        this.toastInstance.show({ timeOut:0 })
    }

    componentWillMount() {
        const notifConn = new signalR.HubConnectionBuilder().withUrl("/notif").build();
        notifConn.on("ReceiveMessage", function (msg) {
            this.setState = ({ message: msg })

        });
        notifConn.start().then(function () {
            notifConn.invoke("SendNotification");

        }).catch(function (er) {
            console.log(er.toString());
        });


    }

Upvotes: 6

Views: 1473

Answers (3)

Alok Mali
Alok Mali

Reputation: 2881

You should do it by this way...

this.setState({ message: msg })

setState is a function which modifies the current state of the component's variable and force component to re-render the result. Although you can do it like (Strongly Not Recommended)

this.state.message = msg; 

But this will not inform component to re-render.

Upvotes: 0

Merci Dieu KIMPOLO
Merci Dieu KIMPOLO

Reputation: 443

Can you write your constructor this way:

constructor(props) {
    super(props);
    this.position = { X: 'Right', Y: 'Top' }
    this.state = { message:null}

}

and use this for changing the state: this.setState({message:msg})

Upvotes: 0

Raicuparta
Raicuparta

Reputation: 2115

setState is a function, so

this.setState = ({ message: msg })

Should instead be

this.setState({ message: msg })

Besides, your function will not be able to access your classe's this. So instead of a normal anonymous function, you should go with an arrow function that preserves the context:

notifConn.on("ReceiveMessage", (msg) => {
   this.setState({ message: msg })
});

Upvotes: 4

Related Questions