Skip to content

Pagination + Moving to dependency array for onMount + onUpdate

Compare
Choose a tag to compare
@iamthesiz iamthesiz released this 19 Nov 07:36
· 198 commits to master since this release
071a6b9

🚨⚠️ This release has breaking changes! ⚠️🚨

  • removed onMount and onUpdate in exchange for accepting a dependency array as the last argument of useFetch
  • added onNewData to be used for merging new fetched data with current data for pagination

onMount AND onUpdate Pagination example

import useFetch, { Provider } from 'use-http'

const Todos = () => {
  const [page, setPage] = useState(1)

  const { data, loading } = useFetch({
    path: `/todos?page=${page}&amountPerPage=15`,
    onNewData: (currTodos, newTodos) => [...currTodos, ...newTodos], // appends newly fetched todos
    data: []
  }, [page]) // runs onMount AND whenever the `page` updates (onUpdate)

  return (
    <ul>
      {data.map(todo => <li key={todo.id}>{todo.title}</li>}
      {loading && 'Loading...'}
      {!loading && (
        <button onClick={() => setPage(page + 1)}>Load More Todos</button>
      )}
    </ul>
  )
}

const App = () => (
  <Provider url='https://example.com'>
    <Todos />
  </Provider>
)

onMount only example

import useFetch, { Provider } from 'use-http'

function Todos() {
  const { loading, error, data } = useFetch({
    path: '/todos',
    data: []
  }, []) // onMount

  return (
    <>
      {error && 'Error!'}
      {loading && 'Loading...'}
      {data.map(todo => (
        <div key={todo.id}>{todo.title}</div>
      )}
    </>
  )
}

const App = () => (
  <Provider url='https://example.com'>
    <Todos />
  </Provider>
)

onUpdate only example:

If for some reason you need to only do onUpdate without onMount, you will have to use managed state for this.

import useFetch, { Provider } from 'use-http'

function Todos() {
  const { loading, error, get, data } = useFetch({
    path: '/todos',
    data: []
  })

  const mounted = useRef(false)
  useEffect(() => {
    if (mounted.current) {
      // onUpdate only
      get()
    }
    mounted.current = true
  })

  return (
    <>
      {error && 'Error!'}
      {loading && 'Loading...'}
      {data.map(todo => (
        <div key={todo.id}>{todo.title}</div>
      )}
    </>
  )
}

const App = () => (
  <Provider url='https://example.com'>
    <Todos />
  </Provider>
)