pauleveritt / eleventy-tsx

Demo of Eleventy 3, ESM, and TS/TSX
10 stars 1 forks source link

Data files do not seem to be injected in tsx layouts #1

Open AoDev opened 2 days ago

AoDev commented 2 days ago

Hi, nice project you did here! I am new to Eleventy and really wanted to start with typescript / tsx.

I didn't quite figure out how to use data in the tsx layouts. My final goal is to be able to run an async call and get data from somewhere.

I first tried with static data

global in _data folder,

like _data/fruits.js or _data/fruits.json ["apple", "pear"]

And expected to be able to use it

export function MainLayout({ fruits }: {fruits: string[]): JSX.Element {...}

But it's not injected.

end goal

Would be to have some async call somewhere. For example:

pokemons.ts

const apiUrl = 'https://pokeapi.co/api/v2/pokemon?limit=10'

export async function getPokemons(): Promise<string[]> {
  const response = await fetch(apiUrl)
  const data = await response.json()
  return data.results.map((pokemon: {name: string}) => pokemon.name)
}

And be able to use it in

export function MainLayout({ pokemons }: ViewProps): JSX.Element {
  return (
    ... <div> {pokemons.map(....)}
  )
}
pauleveritt commented 20 hours ago

For the second case, it isn't part of the data cascade nor does it rely on anything in the 11ty configuration. You could just call it from the MainLayout function, rather than counting on it to be injected, right?

It's a nice thing about this approach. It doesn't rely on some magical thing to get a callable into the "template" scope. It's just import it and call it.

For the former...11ty is going to hand a "layout" the same thing it a JavaScript Template function. So data should have access to the data cascade.

AoDev commented 18 hours ago

Sorry for my ignorance here but I do not understand how I'd call an async function in MainLayout. It returns a JSX Element. It's not React where I could for example use useEffect to run an async operation that gets the data and re-renders. What am I missing?

pauleveritt commented 3 hours ago

11ty allows marking a JavaScript Template function as async which then means you can do an await on a line in the function.