Search code examples
javascriptsolid-js

SolidJS: How to trigger refetch of createResource?


I have a createResource which is working:

const fetchJokes = async (programmingOnly) => {
  alert(programmingOnly);
  return (await fetch(`https://official-joke-api.appspot.com/jokes/${programmingOnly?'programming/':''}ten`)).json();
}
//...
const [jokes, { mutate, refetch }] = createResource(programmingOnly(), fetchJokes);

Now I want to change the programmingOnly boolean via it's signal:

const [programmingOnly, setProgrammingOnly] = createSignal(true);
//...
Programming Only: <input type="checkbox" checked={programmingOnly()}
        onInput={()=>{setProgrammingOnly(!programmingOnly());refetch();}}> </input>

But this does not work, the alert fires upon subsequent attempts, but with undefined as arg, and nothing happens with the data.

What is the SolidJS way of approaching this?


Solution

  • I believe the problem here is the signal is getting set with false every time. Since programmingOnly is a signal it should be accessed as a function to retrieve its value.

    Ie..

    setProgrammingOnly(!programmingOnly)
    
    // should be
    setProgrammingOnly(!programmingOnly())
    

    You should not need to call refetch or do anything else for the example to work.