react-console icon indicating copy to clipboard operation
react-console copied to clipboard

First call to `.log()` can throw an exception?

Open erantapaa opened this issue 8 years ago • 2 comments

I've modified the simple echo demo to include a button which calls .log() with some text when pressed.

The app will throw an exception if the very first thing I do is press the button. If, however, I first enter some text (including a CR) the button works correctly.

The exception is:

TypeError: Cannot read property 'message' of undefined
default_1.log
C:/Users/Admin/Documents/Work/console-bug/node_modules/react-console-component/lib/react-console.js:151
  148 |     messages[_i - 0] = arguments[_i];
  149 | }
  150 | var log = _this.state.log;
> 151 | log[_this.state.log.length - 1].message.push({ value: messages });
  152 | _this.setState({
  153 |     log: log,
  154 | }, _this.scrollIfBottom());

Source for App.js (using react-console-component 0.6.1):

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Console from 'react-console-component'
import 'react-console-component/main.css'

class App extends Component {
  child: { console?: Console } = {}
  echo = (text) => {
    this.child.console.log(text)
    this.child.console.return()
  }
  click = () => {
    this.echo("I was clicked!!!")
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        <Console ref={ (r) => this.child.console = r}
                 handler={this.echo} autofocus={true} />
        <button onClick={this.click}>Click Me</button>
      </div>
    );
  }
}

export default App;

erantapaa avatar Dec 27 '17 16:12 erantapaa

Calling console.acceptLine() prior to console.log(text) may help alleviate this bug

e.g. <Console ref={ (r) => {this.child.console = r; r.acceptLine();}} handler={this.echo} autofocus={true} />

dcollien avatar Jan 22 '18 07:01 dcollien

This is because the log method adds messages to an associated command. At present, if you call log without a command, there is no sensible place to record the message. What is your use case for this functionality? This should only occur before a command is entered. Are you able to use the welcomeMessage for your purpose?

astralarya avatar Jan 07 '19 18:01 astralarya