Last active
June 15, 2023 23:24
-
-
Save pratikdevdas/86ffc5a9aea8e950c83827a3113bdad6 to your computer and use it in GitHub Desktop.
Fetching data from external api in remix. This code only runs on server side. Genres from TMDB has been used using a env hiding the Auth Token.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { json, type V2_MetaFunction } from '@remix-run/node' | |
import { useLoaderData } from '@remix-run/react' | |
export const meta: V2_MetaFunction = () => { | |
return [ | |
{ title: 'New Remix App' }, | |
{ name: 'description', content: 'Welcome to Remix!' } | |
] | |
} | |
interface Genres { | |
id: number | |
name: string | |
} | |
const url = 'https://api.themoviedb.org/3/genre/movie/list?language=en' | |
const options = { | |
method: 'GET', | |
headers: { | |
accept: 'application/json', | |
Authorization: `Bearer ${process.env.AUTH_TOKEN}` | |
} | |
} | |
const getData = async () => { | |
try { | |
const response = await fetch(url, options) | |
//destructured object because its convenient to infer the type in loader function | |
const { genres } = await response.json() | |
//or // const data = await response.json() | |
return genres | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
export async function loader() { | |
const genres:Genres[] = await getData() | |
//or | |
/* | |
const data = await getData() | |
const genres:Genres[] = data.genres | |
*/ | |
return genres | |
} | |
export default function Index() { | |
const genres = useLoaderData<typeof loader>() | |
return ( | |
<div> | |
{genres.map((g) => <div key={g.id}>{g.id}</div>)} | |
</div> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This is what the api returns | |
{ | |
"genres": [ | |
{ | |
"id": 53, | |
"name": "Thriller" | |
}, | |
{ | |
"id": 10752, | |
"name": "War" | |
}, | |
{ | |
"id": 37, | |
"name": "Western" | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment