Skip to content

RTKQ: How to fill endpoint cache on app start? #1366

Closed
@MaximKondratev

Description

@MaximKondratev

In my app i create store based on some initial data, passed to client. If i have data I need to fill an endpoint cache on app start so it do no call endpoint when query run later with same arg.

const api = createApi({
    ...
    endpoints: (builder) => ({
        myEndpoint: builder.query({
             query: (id) => `myEp/${id}`,
        }),
    })
})

type AppInitialData = {
    prefilled: {
        id: number;
        data: SomeData;
    } | null
}

const createStore = (appInitialData: AppInitialData) => {
    const store = configureStore({
        reducer: {
            [api.reducerPath]: api.reducer,
        },
        middleware: (getDefaultMiddleware) => {
            return getDefaultMiddleware().concat(data.middleware);
        },
    });
    
    if (appInitialData.prefilled) {
        // fill myEndpoint cache for appInitialData.prefilled.id with appInitialData.prefilled.data
    }
    
   return store;
}

// later
// initialId is the same as prefilled.id in AppInitialData
const MyComponent = ({ initialId }) => {
    const [id, setId] = useState(initialId);
    // On first run query data is filled and do not produce call to an endpoint. User sees result immediately
    const query = useMyEndpointQuery(id);
    return ...
}

i tried to call updateQueryData right after configureStore

dispatch(api.util.updateQueryData('myEndpoint', prefilled.id, (draft) => {
    draft = prefilled.data;
}));

but it did nothing. i guess it is impossible to update a query that was not initiated.

so i tried to call initiate and then updateQueryData

dispatch(api.endpoints.myEndpoint.initiate(prefilled.id));
dispatch(api.util.updateQueryData('myEndpoint', prefilled.id, (draft) => {
    draft = prefilled.data
}))

but initiate call produces request that i dont need. updateQueryData still does nothing, i guess because query is in pending state.

Is there any way to achieve this behavior? Or did i miss something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions