Skip to content

Repository files navigation

Newsdata.io logo

Newsdata.io React.js Client

npm versionnpm downloadsCIReactLicenseOpenAPI

Official React hooks SDK for the Newsdata.io News API. Drop-in useLatestNews, useArchiveNews, useCryptoNews, useMarketNews, useNewsCount, … hooks plus a <NewsDataProvider> to share one client. Built on the same proven core as the Node client — validation, typed errors, retries with exponential backoff — and ships first-class TypeScript definitions.

Zero runtime dependencies, no build step, React 18+ as a peer dependency.

Installation

npm install newsdataapi
# react is a peer dependency
npm install react

Quickstart

import{NewsDataProvider,useLatestNews}from'newsdataapi';functionHeadlines(){const{ data, error, isLoading }=useLatestNews({q: 'bitcoin',country: ['us','gb'],language: 'en',});if(isLoading)return<p>Loading…</p>;if(error)return<p>Error: {error.message}</p>;return(<ul>{data.results.map((article)=>(<likey={article.article_id}><ahref={article.link}>{article.title}</a></li>))}</ul>);}exportdefaultfunctionApp(){return(<NewsDataProviderapiKey={process.env.REACT_APP_NEWSDATA_API_KEY}><Headlines/></NewsDataProvider>);}

Hooks

HookEndpointNotes
useLatestNews(params)/1/latestReal-time news
useArchiveNews(params)/1/archiveHistorical news
useNewsSources(params)/1/sourcesAvailable sources (single page)
useCryptoNews(params)/1/cryptoCryptocurrency news
useMarketNews(params)/1/marketMarket / financial news
useNewsCount(params)/1/countAggregate counts (requires from_date, to_date)
useCryptoCount(params)/1/crypto/countAggregate crypto counts
useMarketCount(params)/1/market/countAggregate market counts

Every hook has the same shape:

const{ data, error, isLoading, refetch }=useLatestNews(params,options);
  • data — the API response (null until the first fetch resolves)
  • error — a typed NewsdataError (null on success)
  • isLoadingtrue while a request is in flight
  • refetch() — re-run the request; returns the underlying Promise

options

useLatestNews(params,{enabled: false})// skip the request until enabled

options.enabled (default true) defers fetching — handy when params aren't ready (e.g. waiting on user input).

Parameter values

Values can be a single string or an array of strings (sent comma-joined), and parameter names are case-insensitive — qInTitle and qintitle are equivalent:

useLatestNews({country: ['us','gb'],language: 'en',size: 20});

Inline param objects are safe — the hook compares by value, not reference, so re-renders only re-fetch when the values change.

Provider

Two ways to wire it up:

// 1. Let the provider construct the client.<NewsDataProviderapiKey="..."options={{timeout: 10_000,maxRetries: 3}}><App/></NewsDataProvider>// 2. Or pass your own pre-built client (full control over its lifecycle).import{NewsDataApiClient}from'newsdataapi';constclient=newNewsDataApiClient(apiKey);<NewsDataProviderclient={client}><App/></NewsDataProvider>

Anywhere inside the provider you can grab the client directly:

import{useNewsDataClient}from'newsdataapi';functionExportButton(){constclient=useNewsDataClient();return<buttononClick={()=>client.archiveApi({q: 'x'}).then(save)}>Export</button>;}

Errors

All hook errors are instances of the typed hierarchy from the core SDK:

import{NewsdataValidationError,NewsdataAuthError,NewsdataRateLimitError,NewsdataApiError,NewsdataNetworkError,}from'newsdataapi';if(errorinstanceofNewsdataRateLimitError){console.log('retry after',error.retryAfter,'seconds');}
NewsdataError (catch-all base)
├── NewsdataValidationError (.param)
├── NewsdataApiError (.statusCode, .responseBody)
│ ├── NewsdataAuthError (401 / 403)
│ ├── NewsdataRateLimitError (429; .retryAfter)
│ └── NewsdataServerError (5xx)
└── NewsdataNetworkError (.cause)

Validation errors are thrown before the request is sent (no API quota spent) — e.g. setting q and qInTitle together, an unsupported parameter for that endpoint, or missing from_date/to_date on a count endpoint.

Direct client access

You can also use the underlying client without React — same surface as newsdata-nodejs-client:

import{NewsDataApiClient}from'newsdataapi';constclient=newNewsDataApiClient(apiKey,{timeout: 10_000});// scroll: follow nextPage cursors and merge.constmerged=awaitclient.latestApi({q: 'news',scroll: true,maxResult: 200});// paginate: async generator, one page at a time.forawait(constpageofclient.latestApi({q: 'news',paginate: true,maxPages: 5})){console.log(page.results.length);}

Development

npm install
npm test# node:test, 34 tests, no API key required

Related libraries

Official Newsdata.io clients across languages and runtimes:

Also see free news datasets for ML / NLP work.

License

MIT

About

Official React hooks SDK for the Newsdata.io News API — useLatestNews, useCryptoNews, useMarketNews & more with validation, retries, and typed errors.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages