0

Constructor Getting Called Twice in react component.

When i refresh on link => http://localhost:3000/chat-room/foo/bar inside my costructor a console log statement get logged twice. I can't figure out why?.



ChatBox.js

import React, { Component } from 'react'
import Axios from 'axios';

export default class ChatBox extends Component {
    constructor(props) {
        super(props);
        const { rName, name } = this.props.match.params;
        this.state = {
            rName, 
            name,
            message: ''
        }
        console.log('called');    
    }
    componentDidMount(){
        const {rName, name} = this.state; 
        this.ws = new EventSource(`http://localhost:1337/event-stream/?rName=${rName}&name=${name}`);
        this.ws.onmessage = function (event) {
            console.log('called');
        }
    }
    handleInput = (event) => {
        this.setState({
            ...this.state,
            [event.target.name]: event.target.value
        })
    }
    handleSubmit = (event) => {
        event.preventDefault();
        const { rName, name, message } = this.state;
        Axios.post('http://localhost:1337/message', { rName, name, message }); 
    }
    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label>New Message</label>
                    <input type="text" name="message" onChange={this.handleInput} />
                    <button className="btn">Send</button>
                </form>
            </div>
        )
    }
}
  • Possible because you have React.StrictMode enabled for your app – Shubham Khatri Jun 15 '20 at 11:47
  • now its working fine, thank you, you were right, but can you please elaborate me why this happened due to strict mode? – Sanskar Bansal Jun 15 '20 at 11:49
  • Check https://stackoverflow.com/questions/61920074/double-console-log-except-for-componentdidmount-in-react/61920352#61920352. React intentionally invokes certain functions twice so as to help detect sideeffects – Shubham Khatri Jun 15 '20 at 11:54

0 Answers0