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 text
function 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 text
export 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.