S
SolidJS10mo ago
markus

CreateResource does not update as expected

I'm new to Solid, please forgive me if that is a total dummy question. I'm using solid router and I have this code:
// this is the fetcher func
const fetchData = async (id: string) => {
const response = await fetch(`/api/xyz/${id}`);
return response.json();
};

export const Page = () => {
const params = useParams();

// A: this does not update on route change
const [data] = createResource(params.id, fetchData);

// B: this works
const [data] = createResource(() => params.id, fetchData);
...

return <SomeDataComponent data={data()} />

}
// this is the fetcher func
const fetchData = async (id: string) => {
const response = await fetch(`/api/xyz/${id}`);
return response.json();
};

export const Page = () => {
const params = useParams();

// A: this does not update on route change
const [data] = createResource(params.id, fetchData);

// B: this works
const [data] = createResource(() => params.id, fetchData);
...

return <SomeDataComponent data={data()} />

}
According to the docs, useParams "retrieves a reactive object containing the current route path paramteres as defined in the Route". I'd like to understand why version A does not cause <SomeDataComponent> to update when the route changes, but version B does.
2 Replies
Brendonovich
Brendonovich10mo ago
You're right about useParams, the problem is createResource. From the docs:
you can additionally pass a source signal as the first argument. The source signal will retrigger the fetcher whenever it changes, and its value will be passed to the fetcher.
you can additionally pass a source signal as the first argument. The source signal will retrigger the fetcher whenever it changes, and its value will be passed to the fetcher.
Version A just retrieves the value of id once and passes it to createResource - remember that components in solid only run once, so that params.id access only runs once. Version B provides a signal that the createResource is able to track, since accessing params.id happens inside the resource rather than outside it
markus
markusOP10mo ago
ah, that makes complete sense, thank you @Brendonovich!
Want results from more Discord servers?
Add your server