S
SolidJS4mo ago
Untlsn

Sugestion for Repeat component

On last stream Ryan show a Repeat components and I like it. Specially that I ofter need to just render something X times. I've check solid-primitive@range, but it's Repeat not work like I expected Can someone tell if this self made component will work good, have any major bugs or just strait up is worst then <For> From my tests it's render properly, dispose only points that are pop'ed and I don't see any warns in console about missing root ect.
function callFunctions(d: (() => void)[]) {
for (let i = 0; i < d.length; i++) d[i]();
}

function Repeat(props: {
count: number;
children: (index: number) => JSX.Element;
fallback?: JSX.Element
}) {

let disposes: (() => void)[] = [];
const disposeAll = () => callFunctions(disposes)
onCleanup(disposeAll)

return createMemo<JSX.Element[] | JSX.Element>((arr) => {
const count = Number(props.count) || 0;
if (count <= 0) {
disposeAll();
return props.fallback || null;
}
if (!Array.isArray(arr)) arr = [];
const prev = arr.length;
if (count < prev) {
arr.length = count;
callFunctions(disposes.splice(count))
} else {
for (let i = prev; i < count; i++) {
arr.push(createRoot((dispose) => {
disposes.push(dispose);
return props.children(i)
}));
}
}
return [...arr];
}, []) as unknown as JSX.Element;
}
function callFunctions(d: (() => void)[]) {
for (let i = 0; i < d.length; i++) d[i]();
}

function Repeat(props: {
count: number;
children: (index: number) => JSX.Element;
fallback?: JSX.Element
}) {

let disposes: (() => void)[] = [];
const disposeAll = () => callFunctions(disposes)
onCleanup(disposeAll)

return createMemo<JSX.Element[] | JSX.Element>((arr) => {
const count = Number(props.count) || 0;
if (count <= 0) {
disposeAll();
return props.fallback || null;
}
if (!Array.isArray(arr)) arr = [];
const prev = arr.length;
if (count < prev) {
arr.length = count;
callFunctions(disposes.splice(count))
} else {
for (let i = prev; i < count; i++) {
arr.push(createRoot((dispose) => {
disposes.push(dispose);
return props.children(i)
}));
}
}
return [...arr];
}, []) as unknown as JSX.Element;
}
3 Replies
Untlsn
UntlsnOP4mo ago
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
bigmistqke
bigmistqke4mo ago
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
bigmistqke
bigmistqke4mo ago
that's how i always do it when i need a component like that
Want results from more Discord servers?
Add your server