Section that only render for specific paths

Hi everyone I'm trying to create a CTA section that renders on every page execpt two specific path names. This is my code:
function CtaSection() {
// Get location and pathname
const location = useLocation();
const pathname = createMemo(() => location.pathname);

// Constant to check if the CTA section can be rendered.
const canRenderCta = createMemo(
() => !EXCLUDED_PATHS_TO_SHOW_CTA.includes(pathname()),
);

// If the CTA section can't be render, return `null` to prevent the render and the request.
if (!canRenderCta()) {
return null;
}

// Request CTA data
const cta = createAsync(() => getCtaSettings());

return (...)
}
function CtaSection() {
// Get location and pathname
const location = useLocation();
const pathname = createMemo(() => location.pathname);

// Constant to check if the CTA section can be rendered.
const canRenderCta = createMemo(
() => !EXCLUDED_PATHS_TO_SHOW_CTA.includes(pathname()),
);

// If the CTA section can't be render, return `null` to prevent the render and the request.
if (!canRenderCta()) {
return null;
}

// Request CTA data
const cta = createAsync(() => getCtaSettings());

return (...)
}
The problem is, If I click on a button to go from /projects/<slug> to /contacts (and /contacts is one of the excluded paths) the section keeps visible until I refresh the page. Any way to fix this?
4 Replies
Daniel Sousa @TutoDS
And if I back from /contacts (after refresh) to /project/<slug> the section doesn't appear too, need to refresh again
Madaxen86
Madaxen862mo ago
As opposed to react, solid components run only once. So there is not early return. Instead you have to make one return statement which is conditional. The solid way is: return <Show when={canRenderCta()} fallback={null} //not necessary >…</Show>
Daniel Sousa @TutoDS
Ok, but how I can prevent the request to be made if canRenderCta() is false?
Madaxen86
Madaxen862mo ago
Move createAsync to a child component which is rendered as a child of the Show component. This way it will only be mounted. You could also use the callback of the show component : <Show …> {() => { …createAsync… return … }} </Show>
Want results from more Discord servers?
Add your server