Skip to content

Instantly share code, notes, and snippets.

@pratikdevdas
Last active June 15, 2023 23:24
Show Gist options
  • Save pratikdevdas/86ffc5a9aea8e950c83827a3113bdad6 to your computer and use it in GitHub Desktop.
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.
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 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