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;
2
Answers
You are correct that you cannot call
useQuery
from the Redux slice code. What I’d suggest here is to use some "undefined" initialgridView
state and use theuseEffect
hook to "initialize" thegridView
value.Something similar to the following example:
Call
useInitializeGridView
somewhere in your app near the root where Redux is in scope, e.g. under the ReduxProvider
component in the ReactTree. Any UI that is dependent on thestate.settings.gridView
value should check first if it is defined, then use the defined true/false value.You can handle this by creating a Redux Thunk action to fetch data and set the initial state and then dispatch the Redux Thunk action from your component.
Example