How to set initialState using Redux Toolkit with data using Apollo’s useQuery?

How to set initialState using Redux Toolkit with data using Apollo’s useQuery?


0

I am trying to call the useQuery hook (something not allowed outside of functional components), in a redux toolkit slice. Is this something that is doable, perhaps using createAsyncThunk or some similar method? My application is built with the MERN stack, so my database is MongoDB, and I’m using Graphql to fetch the data. (I’m ignoring the reducers in this example because I’m just focused on getting the data in and setting it to the initial state.)

import { useQuery } from "@apollo/client";
import { createSlice } from "@reduxjs/toolkit";
import { GET_USER_SETTINGS } from "../graphql/queries/settingsQueries";

const { loading, error, data } = useQuery(GET_USER_SETTINGS);

const { gridView } = data.settings;

const initialState = {
   gridView,
};

const settingsSlice = createSlice({
  name: "settings",
  initialState,
  reducers: {
    setGridViewOff(state) {
      state.gridView = false;
    },
    setGridViewOn(state) {
      state.gridView = true;
    }, 
},
});

export const { setGridViewOff, setGridViewOn } = settingsSlice.actions;

export default settingsSlice.reducer;


Load 5 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *