Jack The Baker
Jack The Baker

Reputation: 1903

ReactJs update state from axios api data

I want to create a small chat app with ReactJS and also laravel api, what I tried so far is:

<Form.TextArea placeholder='say something..' onChange={this.handleChange} value={this.state.message} />
<Button animated className="Btheme-Btn-Success Btheme-Btn" onClick={this.handleSend}>
  <Button.Content visible>Send</Button.Content>
    <Button.Content hidden>
      <Icon name='send' />
    </Button.Content>
</Button>

Here is semantic part, and as you see there is a button and textarea, users can write and by click on send button, send data to api. here is handler and also api call:

async componentDidMount() {
    const data = {
        post_id: this.props.match.params.id
    }
    const result = await API.MessageShow(data); // get from api
    if(result.status === 200){
        this.setState({ data: result.data, loader: ''});
    }
}

Handle Change:

handleChange = (e) => {
    let v = e.target.value;
    this.setState({
        message: v
    })
}

Handle Send:

handleSend = async (e) => {
    e.preventDefault();
    const data = {
        post_id: this.props.match.params.id,
        user_id: this.props.match.params.user,
        message: this.state.message
    }
    const send = await API.sendMessage(data, 'agent'); // send message here
    if(send.status === 201){
        this.setState({
            message: ''
        })
        const data2 = {
            post_id: this.props.match.params.id
        }
        const result = await API.getAgentMessageShow(data2); //update from api here
        if(result.status === 200){
            this.setState({ data: result.data, loader: ''});
        }
    }
}

As you see in code, all messages store in a state called message and I update this state after send has done, this work good, not perfect but it's ok, now I faced with a challenge, (because if other user send a message, current user not gonna see until send a new message to that user) I want update this state automatically, not after trigger click or any handler... I don't want to use auto refresh or something similar. Should I use socket? or it is possible to this with pure reactjs. if your option is socket, please tell me how.

Upvotes: 0

Views: 61

Answers (1)

Ehsan Hejazi
Ehsan Hejazi

Reputation: 196

Auto refresher in specific duration causes lots of pressure on the server and some times will crash it , so we're gonna have to use socket to handle this issue and make server response to client automatically : I'm a nodejs developer so I know nothing about laravel but after integrating socket.io with your backend :

install socket.io for your client side and connect it with your server and server will response to client when new message is available for user

npm i socket.io-client

Upvotes: 1

Related Questions