Commit 42bf2109 authored by Resi Respati's avatar Resi Respati Committed by Luis Alvarez D

[with-typescript] Updated TypeScript example to use API routes (#9073)

* [with-typescript] Updated TypeScript example to use API routes

Next.js 9.0.0 has been out for a while, which supports API routes, but
the examples were never updated to make use of it. This PR adds a simple
example of an API route which also makes use of dynamic routing.

A simple `fetch()` wrapper is also added for example purposes, and the
pages structure have also been updated to dynamic routing.

* Properly link to the dynamic page
parent 52023fe2
...@@ -26,8 +26,8 @@ const Layout: React.FunctionComponent<Props> = ({ ...@@ -26,8 +26,8 @@ const Layout: React.FunctionComponent<Props> = ({
<a>About</a> <a>About</a>
</Link>{' '} </Link>{' '}
|{' '} |{' '}
<Link href="/initial-props"> <Link href="/users">
<a>With Initial Props</a> <a>Users List</a>
</Link> </Link>
</nav> </nav>
</header> </header>
......
...@@ -8,7 +8,7 @@ type Props = { ...@@ -8,7 +8,7 @@ type Props = {
} }
const ListItem: React.FunctionComponent<Props> = ({ data }) => ( const ListItem: React.FunctionComponent<Props> = ({ data }) => (
<Link href={`/detail?id=${data.id}`}> <Link href="/users/[id]" as={`/users/${data.id}`}>
<a> <a>
{data.id}: {data.name} {data.id}: {data.name}
</a> </a>
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
"type-check": "tsc" "type-check": "tsc"
}, },
"dependencies": { "dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "latest", "next": "latest",
"react": "^16.10.1", "react": "^16.10.1",
"react-dom": "^16.10.1" "react-dom": "^16.10.1"
......
import { NextApiRequest, NextApiResponse } from 'next'
import { sampleUserData } from '../../../utils/sample-data'
export default (req: NextApiRequest, res: NextApiResponse) => {
try {
const { id } = req.query;
const selected = sampleUserData.find(data => data.id === Number(id))
if (!selected) {
throw new Error('Cannot find user')
}
res.status(200).json(selected)
} catch (err) {
res.status(404).json({ statusCode: 404, message: err.message })
}
}
import { NextApiRequest, NextApiResponse } from 'next'
import { sampleUserData } from '../../../utils/sample-data'
export default (_: NextApiRequest, res: NextApiResponse) => {
try {
if (!Array.isArray(sampleUserData)) {
throw new Error('Cannot find user data')
}
res.status(200).json(sampleUserData)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
}
import * as React from 'react' import * as React from 'react'
import { NextPageContext } from 'next' import { NextPageContext } from 'next'
import Layout from '../components/Layout'
import { User } from '../interfaces' import { User } from '../../interfaces'
import { findData } from '../utils/sample-api' import Layout from '../../components/Layout'
import ListDetail from '../components/ListDetail' import ListDetail from '../../components/ListDetail'
import { sampleFetchWrapper } from '../../utils/sample-api'
type Props = { type Props = {
item?: User item?: User
...@@ -14,7 +15,7 @@ class InitialPropsDetail extends React.Component<Props> { ...@@ -14,7 +15,7 @@ class InitialPropsDetail extends React.Component<Props> {
static getInitialProps = async ({ query }: NextPageContext) => { static getInitialProps = async ({ query }: NextPageContext) => {
try { try {
const { id } = query const { id } = query
const item = await findData(Array.isArray(id) ? id[0] : id) const item = await sampleFetchWrapper(`http://localhost:3000/api/users/${Array.isArray(id) ? id[0] : id}`)
return { item } return { item }
} catch (err) { } catch (err) {
return { errors: err.message } return { errors: err.message }
...@@ -36,7 +37,7 @@ class InitialPropsDetail extends React.Component<Props> { ...@@ -36,7 +37,7 @@ class InitialPropsDetail extends React.Component<Props> {
return ( return (
<Layout <Layout
title={`${item ? item.name : 'Detail'} | Next.js + TypeScript Example`} title={`${item ? item.name : 'User Detail'} | Next.js + TypeScript Example`}
> >
{item && <ListDetail item={item} />} {item && <ListDetail item={item} />}
</Layout> </Layout>
......
import { NextPage } from 'next' import { NextPage } from 'next'
import Link from 'next/link' import Link from 'next/link'
import Layout from '../components/Layout'
import List from '../components/List' import Layout from '../../components/Layout'
import { User } from '../interfaces' import List from '../../components/List'
import { findAll } from '../utils/sample-api' import { User } from '../../interfaces'
import { sampleFetchWrapper } from '../../utils/sample-api'
type Props = { type Props = {
items: User[] items: User[]
...@@ -11,8 +12,11 @@ type Props = { ...@@ -11,8 +12,11 @@ type Props = {
} }
const WithInitialProps: NextPage<Props> = ({ items, pathname }) => ( const WithInitialProps: NextPage<Props> = ({ items, pathname }) => (
<Layout title="List Example (as Functional Component) | Next.js + TypeScript Example"> <Layout title="Users List | Next.js + TypeScript Example">
<h1>List Example (as Function Component)</h1> <h1>Users List</h1>
<p>
Example fetching data from inside <code>getInitialProps()</code>.
</p>
<p>You are currently on: {pathname}</p> <p>You are currently on: {pathname}</p>
<List items={items} /> <List items={items} />
<p> <p>
...@@ -24,10 +28,12 @@ const WithInitialProps: NextPage<Props> = ({ items, pathname }) => ( ...@@ -24,10 +28,12 @@ const WithInitialProps: NextPage<Props> = ({ items, pathname }) => (
) )
WithInitialProps.getInitialProps = async ({ pathname }) => { WithInitialProps.getInitialProps = async ({ pathname }) => {
// Example for including initial props in a Next.js function compnent page. // Example for including initial props in a Next.js function component page.
// Don't forget to include the respective types for any props passed into // Don't forget to include the respective types for any props passed into
// the component. // the component.
const items: User[] = await findAll() const items: User[] = await sampleFetchWrapper(
'http://localhost:3000/api/users'
)
return { items, pathname } return { items, pathname }
} }
......
import { User } from '../interfaces' import fetch from 'isomorphic-unfetch'
/** Dummy user data. */ export async function sampleFetchWrapper(
export const dataArray: User[] = [ input: RequestInfo,
{ id: 101, name: 'Alice' }, init?: RequestInit
{ id: 102, name: 'Bob' }, ) {
{ id: 103, name: 'Caroline' }, try {
{ id: 104, name: 'Dave' }, const data = await fetch(input, init).then(res => res.json())
] return data
} catch (err) {
/** throw new Error(err.message)
* Calls a mock API which finds a user by ID from the list above.
*
* Throws an error if not found.
*/
export async function findData(id: number | string) {
const selected = dataArray.find(data => data.id === Number(id))
if (!selected) {
throw new Error('Cannot find user')
}
return selected
}
/** Calls a mock API which returns the above array to simulate "get all". */
export async function findAll() {
// Throw an error, just for example.
if (!Array.isArray(dataArray)) {
throw new Error('Cannot find users')
} }
return dataArray
} }
import { User } from '../interfaces'
/** Dummy user data. */
export const sampleUserData: User[] = [
{ id: 101, name: 'Alice' },
{ id: 102, name: 'Bob' },
{ id: 103, name: 'Caroline' },
{ id: 104, name: 'Dave' },
]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment