I'm working on the NetNinja react-router
in-depth #6 tutorial, but I'm trying to do it with typescript. I am fetching data from a JSON object, and I'm using the useLoaderData()
hook and trying to map out the JSON object. I'm just not sure where to declare the type and/or which type to declare. Here is my component:
import { NavLink, Link, Outlet, useLoaderData } from 'react-router-dom'
type Token = {
id: number
name: string
ticker: string
description: string
}
const Tokens = () => {
const tokens = useLoaderData()
return (
<div>
<div>
{tokens.map((token: Token) => (
<Link to='/' key={token.id}>
<p>{token.name}</p>
<p>{token.ticker}</p>
<p>{token.description}</p>
</Link>
))}
</div>
<nav>
<NavLink to='uniswap'>Uniswap</NavLink>
<NavLink to='balancer'>Balancer</NavLink>
</nav>
<Outlet />
</div>
);
}
//loader function
export const tokensLoader = async () => {
const res = await fetch('http://localhost:4000/tokens')
return res.json()
}
export default Tokens;
The JSON object:
{
"tokens": [
{
"id": 1,
"name": "uniswap",
"ticker": "UNI",
"description": "This is the description for Uniswap token"
},
{
"id": 2,
"name": "balancer",
"ticker": "BAL",
"description": "This is the description for Balancer token"
}
]
}
My intuition felt like it should either be something like:
const tokens: Token[] = useLoaderData()
or
type TokenData = {
tokens: Token[]
}
const tokens: TokenData = useLoaderData()
There is a lot going on and it is beyond my current understanding just following this tutorial. Which type should I be declaring and where?