solid-js

SolidJS: Is there a way to pass in an object to the first param of `createResource`


Is there a way to pass in an object to the first param of createResource? For example: I am trying the following and it is not working:

const [val] = createResource(props, req);

I have also tried a few other things including the following:

const [val] = createResource(signal(), req);

const [val] = createResource(["foo","bar"], req);

const [val] = createResource(merged, req);


Solution

  • For the source argument of createResource to be reactive, you need to pass a function that is reading from a signal. Then the createResource will be able to track it and refetch when it changes.

    const [data] = createResource(() => ({ ...props }), fetcher);
    

    Here I'm destructuring props object to read all of its properties within the tracking scope of the source function.

    Playground demo