Issue
I am implementing the new React Router. I am using loader functions to fetch data depending on which element is being loaded.
What I want to happen is regardless of the route some apis should be called. If the url is a certain route then certain additional APIs should be called.
The problem I am having is that the url path parameters are optional.
In my implementation below when the user visits "/"
only defaulNewAPIs
should run. The issue is since those path parameters are optional both loader functions run. getSubmission
gets called with null
params.
const router = createBrowserRouter([
{
path: '/',
element: <AppLayout />,
id: 'root',
loader: () => defaulNewAPIs(),
children: [
{
index: true,
element: <ReferralDetails status="new" />,
path: '/:appTypeId?/:submissionId?',
loader: ({ params }) => getSubmission(params),
},
],
},
])
The reason I need those params to be optional is because my AppLayout
component conditionally renders a header if those params are present.
const AppLayout: React.FC<AppProps> = ({ msalContext }: AppProps) => {
const { appTypeId } = useParams()
const currentUser = { name: msalContext.accounts[0].name }
return (
<>
{!appTypeId && (
<AppHeader
appName="REFERRALS"
currentUser={currentUser}
notificationNumber="4"
/>
)}
<Outlet />
</>
)
}
Solution
Route loaders are always called when the route loads and they are passed the route params, so you can check they exist prior to applying additional logic.
Example:
type ReferralParams = {
appTypeId?: string;
submissionId?: string;
};
{
element: <ReferralDetails status="new" />,
path: '/:appTypeId?/:submissionId?',
loader: ({ params }) => {
const { appTypeId, submissionId } = params as ReferralParams;
if (appTypeId && submissionId) {
return getSubmission(params);
}
return null;
},
},
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.