0

I've integrated react into my astro project with the hope of incorporating some dynamic functionality. It's all working great except when tryin to fetch data from a remote rest api endpoint inside of one of my react components. I'm aware of the top level async, which seems to work fine when I tried it. However, my objective is to create a component that can refresh itself upon the click of a button. So in order to do that I've opted to utilize usestate and useffect hooks for the task. As soon as I try to make the fetch with an async await function inside of the useeffect hook, the component renders without fetching the data. The following code doesn't return anything apart from the heading.

import React, { useState, useEffect } from 'react';

your textfunction UserRecords() { your text const [users, setUsers] = useState([]); your text const [toggle, setToggle] = useState(true);

your text useEffect(() => { your text async function fetchUsers() { your text try { your text const response = await fetch("http://localhost:3001/userInfo"); your text if (!response.ok) { your text throw new Error('Network response was not ok'); your text } your text const userData = await response.json(); your text setUsers(userData); your text } catch (error) { your text console.error("Error fetching or parsing user data:", error); your text } your text }

your text fetchUsers(); your text }, [toggle]);

your text const changeValue = () => { your text setToggle(prevValue => !prevValue); your text };

your text return ( your text <> your text

Heading

your text
    your text {users.map((user) => {user.username})} your text
your text Update your text </> your text ); your text}

your textexport default UserRecords;

I tried the same thing using the solid js framework which I also added to the astro project just to see how it would compare and the results were the same. Top level async seemed to work fine but when trying to use it in the context of states and side effects, it renders everything but the desired data from the endpoint.

Mike
  • 1
  • 1
  • Have you added a client directive to load the React component on the client side? - [Client Directives Reference](https://docs.astro.build/en/reference/directives-reference/#client-directives) – The Otterlord Aug 28 '23 at 13:35
  • Please forgive the messy presentation of my code, I did all of this on a smartphone while on a small roadtrip. I'll try to do better next time. Anyway, before this, I knew little to nothing about the topics of SSG, SSR, and all that stuff. Now, going through it has solved my problem spot on. I now appreciate more than ever before what the folks at astro are doing to make our lives easier. Thanks much Otterlord for the pointer. – Mike Aug 28 '23 at 15:47

0 Answers0