SoFunction
Updated on 2025-04-07

Detailed explanation of small examples of react-refetch usage

Use react-refetch to simplify the code of api to get data

const List = ({data: gists}) => {
 return (
  <ul>
   {(gist => (
    <li key={}>{}</li>
   ))}
  </ul>
 )
}

const withData = url => Part => {
 return class extends Component {
  state = {data: []}

  componentDidMount() {
   fetch(url)
    .then(response =>  ? () : response)
    .then(data => ({data}))
  }

  render() {
   return <Part {...} {...} />
  }
 }
}

const ListWithGists = withData('/users/gaearon/gists')(List)

In the above code, we extract the logic of the API data acquisition using higher-order components. Next, we use react-refetch to simplify the above asynchronous code.

import { connect as refetchConnect } from 'react-refetch'

const List = ({gists}) => {
 if () {
  return <div>loading...</div>
 } else if () {
  return <div>{}</div>
 } else if () {
  return (
    && <ul>
    {(gist => (
     <li key={}>{}</li>
    ))}
   </ul>
  )
 }
}

const ListWithGists = refetchConnect(() => ({gists: `/users/gaearon/gists`}))(List)

It was much more refreshing in an instant. By the way, using the properties provided by react-refetch, and adding loading logic.

Separating list and project responsibilities

It is obvious that the List component is a component that renders the list, and its responsibility is to render the list, but we also deal with the logic of a single Item here, and we can separate it responsibilities. List only does list dyeing, and Gist only renders itself.

const Gist = ({description}) => (
 <li>
  {description}
 </li>
)

const List = ({gists}) => {
 if () {
  return <div>loading...</div>
 } else if () {
  return <div>{}</div>
 } else if () {
  return (
    && <ul>
    {(gist => <Gist key={} {...gist} />)}
   </ul>
  )
 }
}

Use react-refetch to add functionality to Gist

react-refetchThe connect method receives a function as a parameter. This function returns an object. If the value of the result object is a string, then after obtaining the prop, a request will be initiated. However, if the value is a function, it will not be executed immediately, but will be passed to the component for subsequent use.

The value is a string

const connectWithStar = refetchConnect(() => ({gists: `/users/gaearon/gists`}))

The value is a function

const connectWithStar = refetchConnect(({id}) => ({
 star: () => ({
  starResponse: {
   url: `/gists/${id}/star?${token}`,
   method: 'PUT'
  }
 })
}))

const Gist = ({description, star}) => (
 <li>
  {description}
  <button onClick={star}>+1</button>
 </li>
)

Process the Gist component, the star function will be passed to the Gist's prop, and then it can be used in Gist.

connectWithStar(Gist)

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.