use-fetch-mock.js 553 B

123456789101112131415161718192021
  1. import { useEffect } from 'react'
  2. import fetchMock from 'fetch-mock'
  3. /**
  4. * Run callback to mock fetch routes, call restore() when unmounted
  5. */
  6. export default function useFetchMock(callback) {
  7. useEffect(() => {
  8. return () => {
  9. fetchMock.restore()
  10. }
  11. }, [])
  12. // Running fetchMock.restore() here as well,
  13. // in case there was an error before the component was unmounted.
  14. fetchMock.restore()
  15. // The callback has to be run here, rather than in useEffect,
  16. // so it's run before the component is rendered.
  17. callback(fetchMock)
  18. }