Gathering detailed insights and metrics for react-api-data
Gathering detailed insights and metrics for react-api-data
Gathering detailed insights and metrics for react-api-data
Gathering detailed insights and metrics for react-api-data
react-fetch
A component that fetches data from an api
@privy-io/react-auth
React client for the Privy Auth API
@data-client/react
Async State Management without the Management. REST, GraphQL, SSE, Websockets, Fetch
@shipengine/react-api
The `shipengine/react-api` library provides React bindings for the [shipengine/js-api](https://www.npmjs.com/package/@shipengine/js-api) client, with the addition of data sharing and cache management via [React Query](https://tanstack.com/query/latest) (h
npm install react-api-data
Typescript
Module System
Node Version
NPM Version
TypeScript (91.58%)
JavaScript (8.42%)
Total Downloads
43,271
Last Day
42
Last Week
169
Last Month
893
Last Year
12,492
22 Stars
460 Commits
6 Forks
4 Watching
13 Branches
12 Contributors
Latest Version
1.2.0
Package Id
react-api-data@1.2.0
Unpacked Size
178.54 kB
Size
44.14 kB
File Count
141
NPM Version
6.14.9
Node Version
14.15.3
Cumulative downloads
Total Downloads
Last day
10.5%
42
Compared to previous day
Last week
-34.7%
169
Compared to previous week
Last month
46.9%
893
Compared to previous month
Last year
51.3%
12,492
Compared to previous year
25
Automate calling external APIs and handling response data. Supports any API with JSON responses. Uses Fetch for performing API requests, normalizr for handling response data and redux for storing data.
npm install react-api-data
or
yarn add react-api-data
Make sure fetch is available globally, polyfill it if needed to support older environments.
React-api-data requires the installation of the peer-dependencies react-redux, redux-thunk and normalizr. These can be installed with the following command:
npm install redux react-redux redux-thunk normalizr
or
yarn add redux react-redux redux-thunk normalizr
1import { schema } from 'normalizr'; 2import { createStore, applyMiddleware, combineReducers } from 'redux'; 3import { configure, reducer } from 'react-api-data'; 4import thunk from 'redux-thunk'; 5 6// optionally define normalizr response schemas 7 8const authorSchema = new schema.Entity('Author'); 9const articleSchema = new schema.Entity('Article', { 10 author: authorSchema 11}); 12 13// define api endpoints 14 15const endpointConfig = { 16 getArticle: { 17 url: 'http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId/:userId', 18 method: 'GET', 19 responseSchema: articleSchema 20 }, 21 saveArticle: { 22 url: 'http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId', 23 method: 'POST', 24 afterSuccess: ({ dispatch, request, getState }) => { 25 // After successful post, invalidate the cache of the getArticle call, so it gets re-triggered. 26 dispatch(invalidateRequest('getArticle', {articleId: request.params.articleId, userId: getState().userId})); 27 } 28 } 29}; 30 31// Configure store and dispatch config before you render components 32 33const store = createStore(combineReducers({apiData: reducer}), applyMiddleware(thunk)); 34store.dispatch(configure({}, endpointConfig));
1import React from 'react'; 2import { useApiData } from 'react-api-data'; 3 4const Article = (props) => { 5 const article = useApiData('getArticle', { id: props.articleId }); 6 return ( 7 <> 8 {article.request.networkStatus === 'success' && 9 <div> 10 <h1>{article.data.title}</h1> 11 <p>{article.data.body}</p> 12 </div> 13 } 14 </> 15 ); 16} 17
React-api-data supports React Suspense. Suspense can be enabled globally, per endpoint or per Hook/HOC. It is also possible to override the suspense setting for an endpoint or Hook/HOC.
1import React from 'react'; 2import { useApiData } from 'react-api-data'; 3 4const Article = (props) => { 5 const article = useApiData('getArticle', { id: props.articleId }, { enableSuspense: true }); 6 return ( 7 <> 8 {article.request.networkStatus === 'success' && 9 <div> 10 <h1>{article.data.title}</h1> 11 <p>{article.data.body}</p> 12 </div> 13 } 14 </> 15 ); 16}; 17 18const ArticleList = (props) => { 19 return ( 20 <> 21 <Suspense fallback={<ArticleListLoading/>}> 22 {props.articles.map(article => <Article articleId={article.id}/>} 23 </Suspense> 24 </> 25 ); 26} 27
1import React, { useState } from 'react'; 2import { useApiData } from 'react-api-data'; 3 4const PostComment = props => { 5 const [comment, setComment] = useState(''); 6 const postComment = useApiData('postComment', undefined, { 7 // If a certain call requires a different config from what you've defined in the api endpoint config, you can pass config overrides as the third argument. 8 autoTrigger: false, 9 }); 10 const { networkStatus } = postComment.request; 11 const onSubmit = () => { 12 postComment.perform({ id: props.articleId }, { comment }); 13 }; 14 return ( 15 <> 16 {networkStatus === 'ready' && ( 17 <div> 18 <input 19 onChange={event => setComment(event.target.value)} 20 placeholder="Add a comment..." 21 /> 22 <button onClick={onSubmit}>Submit</button> 23 </div> 24 )} 25 {networkStatus === 'loading' && <div>Submitting...</div>} 26 {networkStatus === 'failed' && ( 27 <div> 28 Something went wrong. 29 <button onClick={onSubmit}>Try again</button> 30 </div> 31 )} 32 {networkStatus === 'success' && <div>Submitted!</div>} 33 </> 34 ); 35};
Calling external API endpoints and storing response data in your redux state can create bloat in your code when you have multiple endpoints, especially in CRUD applications. This package is the result of eliminating repetitive code around API calls and centralizing the concerns of fetching and storing API data into one single package. It provides an easy to use interface that aims to minimize the amount of code needed to use data from external APIs, while maintaining maximum flexibility to support any non-standard API. The idea is that you can just bind data from a given API endpoint to your component, react-api-data takes care of fetching the data if needed, and binding the data to your component.
Responses from successful API calls will be kept in memory so the same call won't be re-triggered a second time. This is especially useful when using withApiData for the same endpoint on multiple components. You can set a cacheDuration to specify how long the response is considered valid, or to disable the caching entirely.
1export default { 2 getArticle: { 3 url: 'http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId/:userId', 4 method: 'GET', 5 cacheDuration: 60000, // 1 minute 6 }, 7 getComments: { 8 url: 'http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId', 9 method: 'GET', 10 cacheDuration: 0, // no caching, use with caution. Preferably set to a low value to prevent multiple simultaneous calls. 11 }, 12 getPosts: { 13 url: 'http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId', 14 method: 'GET' 15 // Infinite caching 16 }, 17}
1import { useApiData } from 'react-api-data'; 2 3const Articles = props => { 4 const getArticles = useApiData('getArticles'); 5 return ( 6 <> 7 {/* ... */} 8 <button onClick={getArticles.invalidateCache}>Refresh</button> 9 </> 10 ); 11} 12
Using the useActions api to invalidate the cache of a specific endpoint.
1import { useActions} from 'react-api-data'; 2 3const Articles = props => { 4 const actions = useActions(); 5 return ( 6 <> 7 {/* ... */} 8 <button onClick={() => actions.invalidateCache('getArticle', {id: '1234'})}>Refresh</button> 9 </> 10 ); 11} 12
1import { useActions} from 'react-api-data'; 2 3const LogoutComponent = props => { 4 const actions = useActions(); 5 return ( 6 <> 7 {/* ... */} 8 <button onClick={() => actions.purgeAll()}>Logout</button> 9 </> 10 ); 11}
1export const globalConfig = { 2 setRequestProperties: (defaultProperties) => ({ 3 ...defaultProperties, 4 credentials: 'include', 5 }) 6};
There might be situations where default parameters are needed, for example when using a language in a URL. These default parameters can be set with the defaultParams
object in your endpointConfig:
1const endpointConfig = { 2 getData: { 3 url: `${BASE_URL}/:language/getData.json`, 4 method: 'GET', 5 defaultParams: { 6 language: 'en', 7 }, 8 }, 9};
You can set default values for multiple parameters or only part of the parameters. Their value should be either a string
or a number
.
Please note that these defaultParams
will be overwritten if they are explicitly set in the request paramaters.
1const connectApiData = withApiData({ 2 items: 'getItemsInList' 3}, (ownProps, state) => ({ 4 items: [{listId: 1}, {listId: 2}, {listId: 3}] 5})); 6 7const ItemsList = (props) => { 8 if (props.items.every(item => item.request.networkStatus === 'success')) { 9 return ( 10 <ul> 11 {props.items.map(item => (<li>{item.data.title}</li>))} 12 </ul> 13 ); 14 } 15 return <p>Loading...</p>; 16} 17 18export default connectApiData(ItemsList);
1 // Use the callback of redux-persist to dispatch the afterRehydrate function. 2 // This will make sure all loading states are properly reset. 3 const persistor = persistStore(store, {}, () => store.dispatch(afterRehydrate())); 4 store.dispatch(configure({}, endpointConfig)); 5 return { 6 store, 7 persistor, 8 };
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
Found 1/6 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
17 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More