anesthetic
anesthetic

Reputation: 315

Reload child with timer

I have a save prompt that appears when various parent components have data submitted to the server. The save prompt is a very simple component:

export class PromptComponent extends React.Component<{}, {}> {
constructor(props: any) {
    super(props)
}
public render(): JSX.Element {
    return (
        <div>
            {this.props.showAlert ? (
                <div id='alert-prompt'>
                    <span>{this.props.children}</span>
                </div>
            ) : null}
        </div>
    )
}
}

My issue is that in the parent, my showAlert prop is a reflection of the parent state doing the following function:

    const closeAlert = () => {
        const closeModal = () => this.setState({
            showAlert: false,
        })
        setTimeout(closeModal, 1000)
    }
    this.setState(
        {
            showAlert: true,
        },
        () => closeAlert()
    )

So this gets redundant if I have to put this code in every parent, and have them keep track of the state of the alert. Is there a more efficient way to do this with less code? Ideally I would like to move the timer-dependent state into the actual alert component itself.

Upvotes: 0

Views: 100

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53954

Define a callback (useCallback props) function to be used within the child component.

Check this example:

class App extends React.Component {
  render() {
    return (
      <Flexbox>
        <PromptComponent
          useCallback={callback => {
            setTimeout(() => {
              callback();
            }, 1000);
          }}
        >
          Hello
        </PromptComponent>
      </Flexbox>
    );
  }
}

Move the show state to your child component and use the callback:

export default class PromptComponent extends React.Component {
  state = {
    show: true
  };

  componentDidMount() {
    this.props.showAlert(() => this.setState({ show: false }));
  }

  render() {
    return (
      <div>
        {this.state.show && (
          <div id="alert-prompt">
            <span>{this.props.children}</span>
          </div>
        )}
      </div>
    );
  }
}

This way you decouple the state from your parent component, also your callback is a generic one, so in future, you can change it to setInterval or anything else.

Edit Q-56823769-ShowComponentTimeout

Upvotes: 1

Related Questions