I'm trying to integrate this following CodeSandbox project into my own project. Upon navigating to the Example
component, however, I'm getting a 404 error: Error: Request failed with status code 404
. The API is querying the following endpoint: http://localhost:3000/api/projects?cursor=0
, but that endpoint doesn't return anything.
For completeness, here's code that comprises my component. I excluded the QueryClientProvider
because it already exists in my index.js
.
import React from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import { useInfiniteQuery } from "react-query";
import useIntersectionObserver from "./hooks/useIntersectionObserver";
export default function Example() {
const {
status,
data,
error,
isFetching,
isFetchingNextPage,
isFetchingPreviousPage,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
hasPreviousPage,
} = useInfiniteQuery(
"projects",
async ({ pageParam = 0 }) => {
const res = await axios.get("/api/projects?cursor=" + pageParam);
return res.data;
},
{
getPreviousPageParam: (firstPage) => firstPage.previousId ?? false,
getNextPageParam: (lastPage) => lastPage.nextId ?? false,
}
);
const loadMoreButtonRef = React.useRef();
useIntersectionObserver({
target: loadMoreButtonRef,
onIntersect: fetchNextPage,
enabled: hasNextPage,
});
return (
<div>
<h1>Infinite Loading</h1>
{status === "loading" ? (
<p>Loading...</p>
) : status === "error" ? (
<span>Error: {error.message}</span>
) : (
<>
<div>
<button
onClick={() => fetchPreviousPage()}
disabled={!hasPreviousPage || isFetchingPreviousPage}
>
{isFetchingNextPage
? "Loading more..."
: hasNextPage
? "Load Older"
: "Nothing more to load"}
</button>
</div>
{data.pages.map((page) => (
<React.Fragment key={page.nextId}>
{page.data.map((project) => (
<p
style={{
border: "1px solid gray",
borderRadius: "5px",
padding: "10rem 1rem",
background: `hsla(${project.id * 30}, 60%, 80%, 1)`,
}}
key={project.id}
>
{project.name}
</p>
))}
</React.Fragment>
))}
<div>
<button
ref={loadMoreButtonRef}
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage
? "Loading more..."
: hasNextPage
? "Load Newer"
: "Nothing more to load"}
</button>
</div>
<div>
{isFetching && !isFetchingNextPage
? "Background Updating..."
: null}
</div>
</>
)}
<hr />
<Link href="/about">
<a>Go to another page</a>
</Link>
</div>
);
}
The problem likely stems from the project.js
file, to which I made no changes. Should I be running this endpoint some way in my React app, or should it run automatically with react-scripts start
? Or is this a problem specific to next.js
?