Gi Tobias
Gi Tobias

Reputation: 59

Getting error on page refresh using @tanstack/react-query

I have this React app (using Remix.run) and I'm trying to fetch some data. When I come from the main page into my sub-page, everything works fine, I get the data fetched, but when I refresh the sub-page while inside it, I get the error Cannot set properties of null (setting 'innerHTML').... I don't know if I'm doing something wrong, but here is the code I've got so far. It's just test code to see if everything works fine, which apparently it doesn't.

import {
  QueryClient,
  QueryClientProvider,
  useQuery,
} from "@tanstack/react-query";

const queryClient = new QueryClient();

export default function Device2ServerFrameParser() {
  return (
    <QueryClientProvider client={queryClient}>
      <Example />
    </QueryClientProvider>
  );
}

function Example() {
  const { isLoading, error, data } = useQuery({
    queryKey: ["repoData"],
    queryFn: () =>
      fetch("https://jsonplaceholder.typicode.com/posts/1").then((res) =>
        res.json()
      ),
  });

  if (isLoading) return <div>Loading...</div>;

  if (error) return <div>Error</div>;

  return (
    <div>
      <span>{JSON.stringify(data)}</span>
    </div>
  );
}

I don't really understand where the problem is so if anyone can help me out, I would greatly appreciate it!

Upvotes: 0

Views: 872

Answers (1)

Gi Tobias
Gi Tobias

Reputation: 59

I want using a useEffect on the root of the website, where I tried to call document.getElementById before the element was created, so when I refreshed it gave that error. It's fixed now

Solution: create an if statement to check if the HTML element acutally exists before using it: if (document.getElementById(...)) {}

Upvotes: 0

Related Questions