createResource

I'm trying to be able to reuse functions for API calls, like how it's done with React Query, but the value of data.isLoading loses reactivity when I use it in my component.
/// function
export function useGetUserById(id: string) {
const [data] = createResource(() => getUsersIdUser(id));
const [isLoading, setIsLoading] = createSignal(data.loading);

createEffect(() => {
setIsLoading(data.loading);
});

return {
isLoading,
data,
};
}

// Use:

const { data, isLoading } = useGetUserById(
session.userSession.user.id,
);
/// function
export function useGetUserById(id: string) {
const [data] = createResource(() => getUsersIdUser(id));
const [isLoading, setIsLoading] = createSignal(data.loading);

createEffect(() => {
setIsLoading(data.loading);
});

return {
isLoading,
data,
};
}

// Use:

const { data, isLoading } = useGetUserById(
session.userSession.user.id,
);
1 Reply
peerreynders
peerreynders21h ago
This works in the playground:
import { render } from 'solid-js/web';
import { createMemo, createResource } from 'solid-js';

function getUsersIdUser(id: string) {
return new Promise<{ id: string }>((r) => setTimeout(() => r({ id }), 2000));
}

function useGetUserById(id: string) {
const [data] = createResource(() => getUsersIdUser(id));
const isLoading = createMemo(() => data.loading);

return {
isLoading,
data,
};
}

function App() {
const { data, isLoading } = useGetUserById('42');

return (
<div>
<p>{data()?.id}</p>
<p>{String(isLoading())}</p>
</div>
);
}

render(() => <App />, document.getElementById('app')!);
import { render } from 'solid-js/web';
import { createMemo, createResource } from 'solid-js';

function getUsersIdUser(id: string) {
return new Promise<{ id: string }>((r) => setTimeout(() => r({ id }), 2000));
}

function useGetUserById(id: string) {
const [data] = createResource(() => getUsersIdUser(id));
const isLoading = createMemo(() => data.loading);

return {
isLoading,
data,
};
}

function App() {
const { data, isLoading } = useGetUserById('42');

return (
<div>
<p>{data()?.id}</p>
<p>{String(isLoading())}</p>
</div>
);
}

render(() => <App />, document.getElementById('app')!);
https://playground.solidjs.com/anonymous/0173c9a5-3b29-491d-a84a-c98ed76c6fc7
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template

Did you find this page helpful?