0

I'm working with Reactjs and I need to show a message using a setTimeout but it always returns a number to me. Does anyone know the reason?

This is my code:

  messageError = () => {
       return <h1>Error!</h1>
  }

render() {
  return (
   ...
     { this.props.error.code != undefined ?
                            setTimeout(() => { this.messageError() }, 3000) : null }

Thanks!

9
  • Because setTimeout does not return anything like you think here. It returns a positive integer and executes something. Here you are invoking your function but its return value can't be rendered like that. What is your intention here? Why do you want a delay? Commented Sep 6, 2018 at 3:55
  • @devserkan thanks. I just want show the error message. Commented Sep 6, 2018 at 3:57
  • You are welcome. Ok, but why the delay? Commented Sep 6, 2018 at 3:57
  • developer.mozilla.org/en-US/docs/Web/API/… should tell you all you need to know. Commented Sep 6, 2018 at 3:59
  • 2
    Then render your component according to this error condition. You don't need any delay here. Even if you need you can't use setTimeout like that. Commented Sep 6, 2018 at 4:02

3 Answers 3

3

I guess you are doing wrong way. As my understanding you want something else. I'm giving yu one example, it might help.

class MyComponent {
  state = {
    error: false,
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        error: true,
      })
    }, 3000);
  }

  renderMessageError() {
    return <h1>Error</h1>
  }

  render() {
    if (this.state.error) {
      return this.renderMessageError();
    }

    return null; //
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Damn, I was going to give nearly the exact same code :) With a 2 seconds delay and some ternary operator :)
Your code helped me, I solved it using componentWillReceiveProps. Thanks.
I would not suggest to use componentWillReceiveProps, this is going to deprecated in newer version of react. reactjs.org/docs/…
2

This is an asynchronous and you can't expect its return value. The number is the ID of setTimeout, used to clear setTimeout.

Comments

1

Because that is what is supposed to do.

setTimeout doesn't pause execution for the indicated time. It schedules your function to occur later and then returns a value (which is typically a number) that can be used to call that schedule.

The function obviously cannot return a value from the future.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.