0.2.0-rc12 • Published 4 years ago

react-fetch-json-hook v0.2.0-rc12

Weekly downloads
11
License
MIT
Repository
github
Last release
4 years ago

react-fetch-json-hook

Use Isomorphic fetch as React hooks with caching and support for SSR.

Installation

npm install react-fetch-json-hook

Or if using yarn

yarn add react-fetch-json-hook

Usage

FetchConnector

import React from 'react'
import { render } from 'react-dom'

import { createFetchConnector, FetchHookProvider } from 'react-fetch-json-hook'

const connector = createFetchConnector()

const App = () => (
  <FetchHookProvider connector={connector}>
    <MyRootComponent />
  </FetchHookProvider>
)

render(<App />, document.getElementById('root'))

useFetch

import { useFetch } from 'react-fetch-json-hook'

const Dogs = () => {
  const { data, error, loading } = useFetch('/api/dogs')

  if (loading) {
    return <div>Loading...</div>
  }
  if (error) {
    return <div>Error! {error.message}</div>
  }

  return (
    <ul>
      {data.dogs.map(dog => (
        <li key={dog.id}>{dog.breed}</li>
      ))}
    </ul>
  )
}

useTriggerableFetch

import { useTriggerableFetch } from 'react-fetch-json-hook'

const Dogs = () => {
  const { trigger, error, loading } = useTriggerableFetch('/api/dogs')

  if (loading) {
    return <div>Loading...</div>
  }

  if (error) {
    return <div>Error! {error.message}</div>
  }

  return (
    <ul>
      <button onClick={trigger}>Fetch Dogs</button>
      {data && data.dogs.map(dog => <li key={dog.id}>{dog.breed}</li>)}
    </ul>
  )
}

Authorization

import { createFetchConnector } from 'react-fetch-json-hook'

const connector = createFetchConnector({
  requestHeaders: {
    Authorization: '<token>',
  },
})

Server-side rendering

import express from 'express'
import {
  createFetchConnector,
  createFetchSSRManager,
  FetchHookProvider,
} from 'react-fetch-json-hook'
import { renderToString } from 'react-dom/server'

const Hello = () => {
  const { data } = useFetch('/foo')
  return <div>{data && data.join(',')}</div>
}

const app = express()

app.get('/', async (req, res) => {
  const connector = createFetchConnector()
  const renderedHtml = await getMarkupFromTree({
    renderFunction: renderToString,
    tree: (
      <FetchHookProvider connector={connector}>
        <Hello />
      </FetchHookProvider>
    ),
  })

  // const initialStateForHydratation = connector.cache
  res.send(renderedHtml)
})

Highly inspired by react-apollo-hooks

0.2.0-rc12

4 years ago

0.2.0-rc11

4 years ago

0.2.0-rc10

4 years ago

0.2.0-rc9

4 years ago

0.2.0-rc8

4 years ago

0.2.0-rc6

4 years ago

0.2.0-rc7

4 years ago

0.2.0-rc5

4 years ago

0.2.0-rc4

4 years ago

0.2.0-rc3

4 years ago

0.2.0-rc1

4 years ago

0.2.0-rc2

4 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.0

5 years ago