SolidJSS
SolidJSβ€’2y agoβ€’
5 replies
jdgamble555

When to use createEffect

I have a signal that depends on another signal. My todos signal is depended on my
user
signal. When there is a user, I want to subscribe to the todos collection, and when there isn't I want to unsubscribe. When there is again (login), I want to resubscribe (user could change too). Should I use createEffect for this? I thought you shouldn't set a signal inside a signal though? Here is my code:
export function useTodos() {

    const _user = useUser();

    const _store = createStore<{
        todos: TodoItem[],
        loading: boolean
    }>({
        todos: [],
        loading: true
    });

    const user = _user[0];

    const setTodos = _store[1];

    setTodos(v => ({ ...v, loading: true }));

    if (!user.data) {
        setTodos({ loading: false, todos: [] });
        return _store[0];
    }

    const unusbscribe = onSnapshot(

        // query realtime todo list
        query(
            collection(db, 'todos'),
            where('uid', '==', user.data.uid),
            orderBy('created')
        ), (q) => {

            // get data, map to todo type
            const data = snapToData(q);

            /**
             * Note: Will get triggered 2x on add 
             * 1 - for optimistic update
             * 2 - update real date from server date
             */

            // print data in dev mode
            if (process.env.NODE_ENV === 'development') {
                console.log(data);
            }

            // add to store
            setTodos({ loading: false, todos: data });

        });

    onCleanup(unusbscribe);

    return _store[0];
};

Thanks,

J
Was this page helpful?