#Fetching data based on component props

13 messages · Page 1 of 1 (latest)

maiden quail
#

Trying to fetch data in-component because the data fetched is based on a prop. I can't seem to get the component to render to the page and I think it's due to the fact the data fetching is async and happening in-component.

Any idea how I can resolve this problem?

Data fetching needs to be based on framework component props, not astro props.

Here is example react/preact component:

const [data, setData] = useState(null);

  const getPosts = useCallback(
    async function getPosts() {
      const data = await fetch(`...siteurl.../${category}`);

      setData(data);
    },
    [category]
  );

  useEffect(() => {
    getPosts().catch(console.error);
  }, [getPosts])


... return ( data && data.map .....)

Thanks,
Isaac

pliant jolt
#

So the server won't run any of the code in the useEffect block, it only renders the initial state of the component. It should get picked up on the client, though... Have you tried client:only?

maiden quail
#

hm

#

i thought the first instance of useeffect would run

#

i guess technically it's one "frame" after isn't it..

#

I'm pretty sure it would work on client, like everything else.

I'm also not sure I can have the desired result without useEffect or similar setup since I can't await fetch inside of sync react component 🤔

pliant jolt
#

I do think our renderer supports Suspense so maybe that's an option?

maiden quail
#

I'll take a look at Suspense

pliant jolt
#

I don't know if that would solve it, but maybe! Could also consider rendering a placeholder on the server and just fetching as usual on the client?

maiden quail
#

Yeah, maybe. The issue is that it's forefront and ux would lose for sure :/

#

Really all i want is just to use <Component /> in multiple places and just pass a different prop (but needs to be framework prop, not astro :/)

pliant jolt
#

You could maybe wrap the React component with an Astro component and do the fetching in both places? The SSR'd content from Astro could be passed as the children of the React component?

return (data ? data.map... : children)