I am using React-Router and trying to get my loader data using the useParams()
hook, but I get the following error:
Here is my code:
import { useLoaderData, useParams } from "react-router-dom";
export async function githubInfoLoader() {
const { username } = useParams(); //The error shows in this line of code
let url = `https://api.github.com/users/kunal22-gupta`
if (username) url = `https://api.github.com/users/${username}`
const response = await fetch(url);
return response.json();
}
export default function Github() {
const data = useLoaderData();
return (
<div>
<h1 className="text-center text-2xl py-5">
Github followers: {data.followers}
</h1>
<div className="flex justify-center mb-10">
<img
src={data.avatar_url}
alt="pfp"
width={300}
className="rounded-full"
/>
</div>
</div>
);
}
I was trying to get the loader value and fetch github profile data, but I got an error saying hooks can only be used inside of function component.
2
Answers
In React Js, component names must start with a capital letter. try this now its working fine.
React hooks can only be called from React functions and custom React hooks. The
Route
component’sloader
function is neither. Fortunately for you the loader functions are passed the routes path parameters in args.Note also that loader functions also understand how to return
fetch
responses. In other words, you can simply returnfetch
and the data router understand to also unpack the JSON response and return that to the routed component.For more details, see the loader documentation.