Search code examples
javascriptreactjsreact-hooksreact-apolloflicker

How to prevent React hooks from erasing previous data while loading?


I'm trying react hooks and made my first component. Everything is working fine except a flickering problem wile data is loading, here's my component (a simple list of articles, with prev/next pagination) :

function InfoFeed ({ limit, uuid }) {
  const [currentIndex, setCurrentIndex] = useState(1)
  const { data, loading } = useQuery(gql(queries.InfoFeed), {
    variables: {
      offset: (articlesByPage * (currentIndex - 1))
    }
  })
  const { articles } = data

  const incrementCb = () => setCurrentIndex(currentIndex === maxPaginationIndex ? 1 : currentIndex + 1)
  const decrementCb = () => setCurrentIndex(currentIndex === 1 ? maxPaginationIndex : currentIndex - 1)

  return (
    <Panel title="Fil Info">
      <StyledList>
        {articles && articles.map((article, index) => (<InfoItem key={index} article={article}/>))}
      </StyledList>
      <button onClick={incrementCb}>next</button>
      <button onClick={decrementCb}>prev</button>
    </Panel>
  )
}

The problem is : when clicking on prev/next buttons, it launches a server request, loading is automatically set to true, and data is set to undefined. Data being undefined, the article list is empty while loading. I could show a spinner conditionally using the loading variable, but it's a pretty fast request (no spinner required), and it wouldn't prevent the previous data from disappearing, which is the cause of this unwanted flickering.

Any idea how to deal with this ? Thanks!


Solution

  • Solved by migrating to official @apollo/react-hooks bindings, since I was using https://github.com/trojanowski/react-apollo-hooks