nextjs app that uses trpc to fetch the current stock price of appl in typescript

To get started, you'll need to install trpc and its dependencies by running npm install trpc react-trpc. You'll also need isomorphic-unfetch to make the actual request to fetch data.

Next, in your Next.js app, create a pages/api/trpc/[trpc].ts file where [trpc] is the name of your trpc endpoint. In this file, define your trpc service and add a method to fetch the current stock price of Apple using an API such as Yahoo Finance:

index.ts
import { createHandler } from 'trpc';
import fetch from 'isomorphic-unfetch';

export default createHandler<{
  getData: () => Promise<number>;
}>({
  getData: async () => {
    const response = await fetch(
      'https://finance.yahoo.com/quote/AAPL?p=AAPL'
    );
    const html = await response.text();
    // Use a regular expression to extract the current stock price from the HTML.
    const regex = /"regularMarketPrice":{"raw":([\d.]+)/;
    const match = html.match(regex);
    if (!match) {
      throw new Error('Could not find Apple stock price');
    }
    return parseFloat(match[1]);
  },
});
609 chars
21 lines

In this example, the getData method fetches the HTML of the Apple stock page, uses a regular expression to extract the current stock price, and returns it as a Promise<number>.

Finally, in your React component, you can use the useTRPC hook from react-trpc to call the trpc service and display the stock price:

index.ts
import { useTRPC } from 'react-trpc';
import { getData } from '../api/trpc/[trpc]';

export default function StockPrice() {
  const result = useTRPC(getData, null);

  if (result.error) {
    return <div>Error fetching stock price: {result.error.message}</div>;
  }

  if (result.isLoading || !result.data) {
    return <div>Loading...</div>;
  }

  return <div>Apple stock price: ${result.data.toFixed(2)}</div>;
}
416 chars
17 lines

In this example, the useTRPC hook calls the getData method from your trpc service, displays an error message if there was an error fetching the stock price, displays a loading message while the data is being fetched, and displays the current stock price once it's available.

gistlibby LogSnag