Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React apollo query too damn fast

I have a react apollo query that is too fast. The <p>Loading...</p> is shown for a split second before the api query finishes and my results are shown. Is there any way to slow this down or produce a slight delay to prevent this flash of content?

like image 443
thatnzguy Avatar asked Jan 18 '26 09:01

thatnzguy


1 Answers

I don't see anything in Apollo client that lets you do this.

I guess what you want is to display the Loading placeholder only if the content is too long to display. In addition to avoid the flashing of content you describe, you avoid that perceptual performance issue (ie. users will more likely feel something is slow, if there's a Loading... caption, even if it takes the same time)

What you can do?

Solution 1: Use local state

  • Add a showLoading state variable in addition to loading prop from Apollo
  • Only trigger showLoading state if it's been too long

Code example (with a component that already receives the loading prop from Apollo) - to adapt to your own use case...

const SHOW_LOADING_AFTER = 1000

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      showLoading: false
    }
    this.loadingTimeout = setTimeout(() => {
      this.setState({ showLoading: true })
    }, SHOW_LOADING_AFTER)
  }

  componentWillUnmount() {
    clearTimeout(this.loadingTimeout)
  }

  render() {
    if (this.props.loading) {
      return this.state.showLoading ? <p>Loading...</p> : null
    }
    return <p>Ready!</p>
  }
}

Solution 2

Make this generic with a higher order component, or a <Timeout> component wrapping <p>Loading...</p> in the render method to avoid polluting state.

All you would need would be in your render method:

if (this.props.loading) {
  <Timeout ms={SHOW_LOADING_AFTER}><p>Loading...</p></Timeout>
}
like image 97
Pandaiolo Avatar answered Jan 20 '26 02:01

Pandaiolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!