SolidJSS
SolidJS2y ago
10 replies
colinshen

confused about primitives(useEffect,on,createComputed)

I‘m trying to create a primitive for synchronize the search params with signal. I tried different methods, all of them works as expected. I started to think of the apis and got confused.
createEffect in this case run twice
createEffect with on run once
createComputed run twice

1. why some of them run twice
2. when to use on with effect?
3. tracking signal and do some updates, shoud I just use computed?

export function createSearchParameter(param: string): Signal<ParamsValue> {
    const [searchParams, setSearchParams] = useSearchParams();
    const [value, setValue] = createSignal<ParamsValue>(searchParams[param]);
    createEffect(
        on(value, (v) => {
            console.log("create effect on");
            setSearchParams({
                ...searchParams,
                [param]: v,
            });
        }),
    );
    createEffect(() => {
        console.log("create effect");

        setSearchParams({
            ...searchParams,
            [param]: value(),
        });
    });
    createComputed<Accessor<ParamsValue>>((v) => {
        console.log("createComputed");

        setSearchParams({
            ...searchParams,
            [param]: v(),
        });
        return v;
    }, value);
    return [value, setValue];
}
Was this page helpful?