react-api-error-boundary

1.0.0 • Public • Published

react-api-error-boundary

An easy way to centralize API calls on data dependent components

NPM JavaScript Style Guide License: MIT

Install

npm install --save react-api-error-boundary

or

yarn add react-api-error-boundary

Usage

In your App.js, initialize the Provider

import React, { useState, useEffect } from 'react'
import Axios from 'axios'
 
import Data from './MyDataDependentComponent'
import { useErrorBoundary, ErrorBoundaryProvider } from 'react-api-error-boundary'
import ErrorUI from './MyErrorFallbackUI'
import LoadingUI from './MyLoadingFallbackUI'
import logErrorToService from './logErrorToService'
 
<ErrorBoundaryProvider
    loadingUI={LoadingUI}
    errorUI={ErrorUI}
    logError={(e) => logErrorToService(e)}
>
    <Data />
    {/* ...More routes/components here */}
</ErrorBoundaryProvider>

Then use the Context on your page

import React, { useEffect, useState } from 'react'
import Axios from 'axios'
import { useErrorBoundary } from 'react-api-error-boundary'
 
const Data = () => {
    const { makeApiRequest } = useErrorBoundary()
    const [data, setData] = useState('')
 
    useEffect(() => {
        const fetchData = async () => {
            const res = await makeApiRequest(Axios.get('https://reqres.in/api/users'))
 
            setData(JSON.stringify(res))
        }
 
        fetchData()
    }, [])
 
    return <code>{data}</code>
}

License

MIT © shreykumar

Dependents (0)

Package Sidebar

Install

npm i react-api-error-boundary

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

64.1 kB

Total Files

8

Last publish

Collaborators

  • shreykumar