I am simply attempting to get information from an API that outputs JSON. But no matter what I do it tells me I'm calling the hooks incorrectly, even though from my understanding of the documentation I am implementing it correctly.
I've restarted the application 4 times fresh and regardless of npm ls react outcome it still errors. even if i have 1 react or 7 deduped. Makes no difference.
It must be something stupid I'm doing, because I can't work it out.
Error below.
The code below is the one in question
datacomp.tsx
import React, { useState, useEffect } from 'react';
let apiGet = "";
export default function DataComponent() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(apiGet);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const json = await response.json();
setData(json);
} catch (error) {
console.error('Error fetching data:', error);
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h1>Data from API</h1>
<ul>
{data.map((item, index) => (
<li key={index}>{item.name}</li> // Ensure that `item.name` exists in the data structure
))}
</ul>
</div>
);
};
root.tsx
import React, { useState, useEffect } from 'react';
import head from './head';
import changelog from './changelog';
import DataComponent from './datacomp'
export default function base() {
return (
<>
{head()}
{/* {changelog()} */}
{DataComponent()}
</>
);
}
app.tsx
import React, { useState, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import base from './partials/root';
const root = createRoot(document.body);
root.render(base())
The issue is that you are manually invoking your React components. While they are defined as functions, they should be rendered as JSX, e.g. passed to React as JSX markup. The React framework converts the JSX to functions and handles calling them within the React component lifecycle.
Update your code to pass these functions as JSX.
export default function Root() {
return (
<>
{head()}
<DataComponent />
</>
);
}
import Root from './partials/root';
const root = createRoot(document.body);
root.render(<Root />);
I suspect you might also want/need to update the head
call similarly.