reactjsastrojs

How can I fetch data from server inside a .tsx component?


Working on a Astro 5 (beta10) application.
The astro is configured with "output": "server".
I have a .tsx component in which I want to fetch data from an API. (Strapi, a CMS).

Since a sensitive API token is used to fetch the data I need it to happen on the server. So I put astro in "output": "server" mode. But the code is now never called. And when I put client:load on the component it execute on the browser which does not have access to the API Token.

My understanding would be to fetch the data from the parent .astro component and pass it as a props to the .tsx component.

Is this the right understanding or is there a 'good' way to fetch the data from the server inside the .tsx component ?

Below the code of the .tsx component :

const Navbar: React.FC = () => {
  const [navbarTabs, setNavbarTabs] = useState<NavbarTab[]>([]);

  const fetchNavbarTabs = async () => {
    const tabs = await strapiFetch({
      endpoint: "navbar-tabs",
      wrappedByKey: "data",
    });
    setNavbarTabs(tabs);
  };

  useEffect(() => {
    fetchNavbarTabs();
  }, []);

  useEffect(() => {
    console.log(navbarTabs.length);
  }, [navbarTabs]);

  return (
    <></>
  );
};

export default Navbar;


Solution

  • The reason your example doesn't work is because useEffect are never executed on the server (that's how React works, nothing Astro-specific). There are special data-fetching libs for React (like React Query), but if you're using Astro, I would just do as you suggested and fetch the data in the .astro component and pass it into the jsx as props.

    P.S. This is unrelated to the data fetching, but note that "output": "server" mode means you're not building a static site anymore. This may or may not be what you want (you could also set up Netlify or similar to retrigger a static build whenever the content in your CMS changes. But that will take a minute or two, so perhaps you're right that you want output: server, then it will fetch from the CMS every time somebody looks at your website.) See https://docs.astro.build/en/basics/rendering-modes/