, }, { path" /> , }, { path" /> , }, { path"/>

Neither react router dom nor react error boundary npm package catching errors

180 Views Asked by At

I am using react router v6 and react-error-boundary npm package

export const routes: RouteObject[] = [
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/signup",
    element: <Signup />,
  },
  {
    index: true,
    element: <Dashboard />,
    // errorElement: <RouteError />,

  },
];
export default createBrowserRouter([
  {
    element: <App />,
    ErrorBoundary: RouteError ,
    children: routes,
  },
]);

This is my route object

<React.StrictMode>
    <ErrorBoundary fallbackRender={ErrorFallback}>
      <Provider store={store}>
        <RouterProvider router={routes} />
      </Provider>
    </ErrorBoundary>
  </React.StrictMode>

This is my index react file

export default function Dashboard() {
  const queryClient = useQueryClient();
  const userQuery = useQuery(["user", "data"], {
    queryFn: () => getUserData(),
    staleTime: convertTime(5, "min", "ms"),
  });
  React.useEffect(() => {
    queryClient.invalidateQueries();
  }, [queryClient]);
  throw Error("iudnxerif")
  if (userQuery.isLoading) {
    return <Loading />;
  }
  if (userQuery.isError) {
    return <Navigate to="/login" />;
  }
  return (
    <Box>
      <Navbar />
      <Stack>
        <Stack>Users Stories</Stack>
        <Stack>
          <Stack>Posts</Stack>
          <Stack>Chats</Stack>
        </Stack>
      </Stack>
    </Box>
  );
}

this is my dashboard file in which i am intentionally throwing a render error However neither react router dom nor Errorboundary in index file catching the error and backdrop with error stack trace is being displayed. Any help reagrding this will be appreciated

Result Image

1

There are 1 best solutions below

1
Tharuka Dananjaya On

we need to move the line containing throw Error("iudnxerif") after the conditionals, as it currently causes the function to throw an error unconditionally.

import React from "react";
import { useQuery, useQueryClient } from "react-query";
import { Navigate } from "react-router-dom";

import { getUserData } from "../api"; // Assuming you have an API 
function to fetch user data.
import Loading from "./Loading";
import Navbar from "./Navbar";

export default function Dashboard() {
const queryClient = useQueryClient();
const userQuery = useQuery(["user", "data"], {
queryFn: () => getUserData(),
staleTime: convertTime(5, "min", "ms"), // Assuming convertTime is 
 defined elsewhere.
});

React.useEffect(() => {
 queryClient.invalidateQueries();
}, [queryClient]);

if (userQuery.isLoading) {
 return <Loading />;
}

if (userQuery.isError) {
 return <Navigate to="/login" />;
}

throw Error("iudnxerif"); // This line will now throw an error only when 
needed.

return (
<Box>
  <Navbar />
  <Stack>
    <Stack>Users Stories</Stack>
    <Stack>
      <Stack>Posts</Stack>
      <Stack>Chats</Stack>
    </Stack>
  </Stack>
 </Box>
 );
}