React Use API
  • Introduction
  • Usage
    • Getting Started
    • Advanced Usage
      • List API and Pagination
      • Request Control
      • Data Processing
      • Side-Effect Dependencies
      • Watch option
    • TypeScript
  • API
    • useApi
    • State
    • Request Function
    • ApiProvider
    • injectSSRHtml
    • loadApiCache
  • Server Side Rendering
    • SSR Settings
    • Examples
      • Real World Examples
      • With Ant Design
Powered by GitBook
On this page
  • Installation
  • Usage
  • Parameters

Was this helpful?

  1. Usage

Getting Started

Installation & basic usage

Installation

❗Axios is a peer dependency (prerequisite) and it has to be installed

NPM

$ npm i react-use-api axios

Yarn

$ yarn add react-use-api axios

Usage

With ApiProvider

import React from 'react'
import ReactDom from 'react-dom'
import useApi, { ApiProvider } from 'react-use-api'

import App from './App'

// there is only one props "context", which is must given for SSR,
// client side can omit it
ReactDom.render(
  <ApiProvider>
    <App />
  </ApiProvider>,
  document.getElementById('root')
)

Basic Usage

import React from 'react'
import useApi from 'react-use-api'

export const Main = () => {
  const [data, { loading, error }, request] = useApi({
    url: '/api/foo/bar'
  })

  return (
    <>
      {loading && <div>Loading...</div>}
      {error && <div>{error.response.data.errMsg}</div>}
      {data && (
        <>
          <div>Hello! {data.username}</div>
          <button onClick={request}>Reload</button>
        </>
      )}
    </>
  )
}

Parameters

Types

const [data, state, request] = useApi(
  config: ReactUseApi.Config | string,
  opt?: ReactUseApi.Options | ReactUseApi.Options['handleData']
)

Code

const [data, state, request] = useApi(config, options)

// request the API data again
request(config?: ReactUseApi.Config, keepState = true)

Config

const [data, state] = useApi('/api/foo/bar')
// equals to
const [data, state] = useApi({
  url: '/api/foo/bar'
})

PreviousIntroductionNextAdvanced Usage

Last updated 5 years ago

Was this helpful?

The config can be an or a URL string.

Axios Request Config