SolidJSS
SolidJS3mo ago
4 replies
Elipzer

How to use createMemo to process a resource with Suspense

In my component, wrapping my expensive function in a createMemo causes the parent suspense to trigger rather than the suspense in the component with the expensive function.

Here's a simplified example of my component's behavior.
const ConfigureBarSearchMatches = () => {
    const resource = createAsync(async () => {
        await new Promise(resolve => setTimeout(resolve, 300));
        return 'resource';
    });
    const expensive = () => {
        if (!resource()) return null;
        const end = Date.now() + 300;
        while (Date.now() < end); // simulate 300ms cpu
        return resource() + 'expensive';
    };
    const expensiveMemo = createMemo(expensive); // without this memo, I see "loading resource + expensive...", with it, I get the parent suspense
    return (
        <div class="matches">
            <Suspense fallback="loading resource + expensive...">{expensiveMemo()}</Suspense>
        </div>
    );
};
const ConfigureBarSearch = () => {
    // if I use createMemo, I need to add a suspense here or else it falls back to the root suspense.
    return <div><input /><Suspense fallback="parent suspense..."><ConfigureBarSearchMatches /></Suspense></div>
}

[For context, the actual component is fetching a JSON dataset (resource), priming a MiniSearch index (expensive), and then executing a search based on an input signal (omitted)]

Without the createMemo I get the "loading resource + expensive..." that I want, but I need the memo for some further processing on the "expensive" function. Is there a way to get my intended behavior using createMemo but without needing a suspense in the parent component?
Was this page helpful?