3

I want to render my ChatBubble component after an amount of time. But it does not return my component. Instead it returns numbers 2 and 3 as a string.

const Conversation = ({data}) => {
  const { messages } = data;

  return (
    <div>
      {
        messages.map(data => {
          return setTimeout(() => {
            return <ChatBubble key={uniqid()} data={data}/>
          }, data.delay);
        })
      }
    </div>
  );
}

export default Conversation;
3
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Jun 7, 2018 at 17:10
  • @jared yes definetly worth reading for the OP, but that wont help him at this particular problem. Commented Jun 7, 2018 at 17:15
  • @JonasW. meh you're right. I retracted. Commented Jun 7, 2018 at 17:18

1 Answer 1

6

Cause setTimeout returns the id of the timer. You cannot just return something to react and expect some magic to happen. Instead you probably need a stateful conponent like this:

class Conversation extends React.Component {
  constructor(props) {
    super(props);
    this.state = { messages: [] };
  }

  render() {
    return this.state.messages.map(data => (<ChatBubble {...data} />));
  }

  componentDidMount() {
     const {messages, delay} = this.props.data;
     this.interval = setInterval(() => {
       this.setState(prev => ({ messages: prev.messages.concat(messages.shift()) }));
       if(!messages.length) clearInterval(this.interval);
     }, delay);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }
}
Sign up to request clarification or add additional context in comments.

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.