API Reference

API Reference

This is the reference for the utility functions that react-tweet provides for building your own tweet components or simply fetching a tweet. Navigate to the docs for the Twitter theme if you want to render the existing Tweet components instead.

getTweet

import { getTweet, type Tweet } from 'react-tweet/api'
 
function getTweet(
  id: string,
  fetchOptions?: RequestInit
): Promise<Tweet | undefined>

Fetches and returns a Tweet (opens in a new tab). It accepts the following params:

  • id - string: the tweet ID. For example in https://twitter.com/chibicode/status/1629307668568633344 the tweet ID is 1629307668568633344.
  • fetchOptions - RequestInit (Optional): options to pass to fetch (opens in a new tab).

If a tweet is not found it returns undefined.

enrichTweet

import { enrichTweet, type EnrichedTweet } from 'react-tweet'
 
const enrichTweet: (tweet: Tweet) => EnrichedTweet

Enriches a Tweet (opens in a new tab) as returned by getTweet with additional data. This is useful to more easily build custom tweet components.

It returns an EnrichedTweet (opens in a new tab).

useTweet

If your app supports React Server Components, use getTweet instead.

import { useTweet } from 'react-tweet'
 
const useTweet: (
  id?: string,
  apiUrl?: string,
  fetchOptions?: RequestInit
) => {
  isLoading: boolean
  data: Tweet | null | undefined
  error: any
}

SWR hook for fetching a tweet in the browser. It accepts the following parameters:

  • id - string: the tweet ID. For example in https://twitter.com/chibicode/status/1629307668568633344 the tweet ID is 1629307668568633344. This parameter is not used if apiUrl is provided.
  • apiUrl - string: the API URL to fetch the tweet from. Defaults to https://react-tweet.vercel.app/api/tweet/:id.
  • fetchOptions - RequestInit (Optional): options to pass to fetch (opens in a new tab). Try to pass down a reference to the same object to avoid unnecessary re-renders.

We highly recommend adding your own API endpoint in apiUrl for production:

const tweet = useTweet(null, id && `/api/tweet/${id}`)

It's likely you'll never use this hook directly, and apiUrl is passed as a prop to a component instead:

<Tweet apiUrl={id && `/api/tweet/${id}`} />

Or if the tweet component already knows about the endpoint it needs to use, you can use id instead:

<Tweet id={id} />