Is there a way to fetch with Apollo/useQuery from within a store?

Viewed 108

I'm stuck on an architecture issue here - I've been developing my project for the last few months using Apollo cache for local state management and am turning to MobX. My application uses a graph-based data structure and requires me to interact with and manipulate the state in sometimes very complex ways. This control has proven too difficult to do with GraphQL queries and Apollo cache (for me).

That being said, I don't want to move away from GraphQL, I just want to hold my results in a MobX store because of how much freedom it gives me. I just can't figure out how to request GraphQL data from within a MobX store function due to the hooks nature of useQuery.

I can see two options:

#1

Making the requests from within store methods feels messy, forced, and is so far error-prone.

class ProjectStore {
    isLoading = false;
    project;
    tasks = {};

    constructor(projectId) {
        makeAutoObservable(this);
        const [_fetchTasks, { data: taskData }] = useLazyQuery(TASKS_QUERY);
        this._fetchTasks = _fetchTasks;

        let { loading, data } = useQuery(PROJECT_AND_ROOT_TASK_QUERY, {
            variables: { projectId },
        });
        this.isLoading = !!loading;
        this.project = data?.project;
    }

    getTasks(taskIds) {
        let { loading, data } = this._fetchTasks({
            variables: { taskIds },
        });

        console.log(data);
    }
}

export default ProjectStore;

#2

Having the cmpt request the data but not have the means to use it directly feels like bad architecture.

  1. CMPT requests the data in a useQuery.
  2. have useEffect to see when data has landed
  3. cmpt puts the data into the store
  4. store does it's data organization
  5. cmpt reads the data from the store

Any suggestions here? Being a lone developer suck sometimes.

0 Answers
Related