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.ts609 chars21 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.ts416 chars17 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