Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1 Codex Max· openaiHugging Face Frontier Reasoning Traces

Generate a React Native boilerplate with Redux Toolkit Query and offline-first…

  1. User

    Generate a React Native boilerplate with Redux Toolkit Query and offline-first architecture. Configure redux-persist to save to AsyncStorage and include a network connectivity hook that pauses mutations when offline and replays them when online.

  2. Assistant

    Designing offline-first React Native boilerplate

    Outlined a Redux Toolkit Query setup with offline-aware baseQuery that queues mutations when offline using a persisted queue slice, network connectivity slice updated by NetInfo, and a hook that flushes queued mutations when back online; next step is producing the full multi-file TypeScript boilerplate code demonstrating this architecture. Below is a minimal React Native + Redux Toolkit Query “offline‑first” boilerplate. It uses:

    • @reduxjs/toolkit with RTK Query
    • redux-persist + @react-native-async-storage/async-storage
    • @react-native-community/netinfo for connectivity detection
    • An offline mutation queue that pauses mutations when offline and replays them when back online

    You can adapt and expand these patterns to fit your domain and backend.


    src/store/index.ts

    import { combineReducers, configureStore } from '@reduxjs/toolkit';
    import { persistReducer, persistStore } from 'redux-persist';
    import AsyncStorage from '@react-native-async-storage/async-storage';
    import {
      FLUSH,
      REHYDRATE,
      PAUSE,
      PERSIST,
      PURGE,
      REGISTER,
    } from 'redux-persist';
    import networkReducer from '../slices/networkSlice';
    import offlineQueueReducer from '../slices/offlineQueueSlice';
    import { api } from '../services/api';
    
    const rootReducer = combineReducers({
      network: networkReducer,
      offlineQueue: offlineQueueReducer,
      [api.reducerPath]: api.reducer,
    });
    
    const persistConfig = {
      key: 'root',
      storage: AsyncStorage,
      // Persist the offline queue so pending mutations survive reload
      whitelist: ['offlineQueue'],
    };
    
    const persistedReducer = persistReducer(persistConfig, rootReducer);
    
    export const store = configureStore({
      reducer: persistedReducer,
      middleware: getDefaultMiddleware =>
        getDefaultMiddleware({
          serializableCheck: {
            ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
          },
        }).concat(api.middleware),
    });
    
    export const persistor = persistStore(store);
    
    export type RootState = ReturnType<typeof rootReducer>;
    export type AppDispatch = typeof store.dispatch;
    

    src/services/api.ts

    Offline-aware baseQuery. If offline, we short-circuit and push the mutation into the queue instead of hitting the network.

    import {
      BaseQueryFn,
      FetchArgs,
      fetchBaseQuery,
    } from '@reduxjs/toolkit/query/react';
    import { createApi } from '@reduxjs/toolkit/query/react';
    import type { RootState } from '../store';
    import { queueMutation } from '../slices/offlineQueueSlice';
    
    const rawBaseQuery = fetchBaseQuery({
      baseUrl: 'https://your-api.com/',
    });
    
    /**
     * A baseQuery wrapper that queues mutations when offline.
     */
    const offlineAwareBaseQuery: BaseQueryFn<
      string | FetchArgs,
      unknown,
      unknown
    > = async (args, api, extraOptions) => {
      const state = api.getState() as RootState;
      const isOffline = state.network.isConnected === false;
      const isMutation = api.type === 'mutation';
    
      if (isOffline && isMutation) {
        // Queue for later replay
        api.dispatch(
          queueMutation({
            endpointName: api.endpoint,
            args,
            extraOptions,
          }),
        );
    
        // Respond with an offline error so UI can show pending state
        return {
          error: { status: 'OFFLINE', data: 'No network connection' },
        };
      }
    
      return rawBaseQuery(args, api, extraOptions);
    };
    
    export const api = createApi({
      reducerPath: 'api',
      baseQuery: offlineAwareBaseQuery,
      tagTypes: ['Todo'],
      endpoints: builder => ({
        getTodos: builder.query<{ id: number; title: string }[], void>({
          query: () => 'todos',
          providesTags: ['Todo'],
        }),
        addTodo: builder.mutation<{ id: number; title: string }, { title: string }>(
          {
            query: body => ({
              url: 'todos',
              method: 'POST',
              body,
            }),
            invalidatesTags: ['Todo'],
          },
        ),
      }),
    });
    
    export const { useGetTodosQuery, useAddTodoMutation } = api;
    

    src/slices/networkSlice.ts

    Tracks connectivity state.

    import { createSlice, PayloadAction } from '@reduxjs/toolkit';
    
    type NetworkState = {
      isConnected: boolean | null;
    };
    
    const initialState: NetworkState = {
      isConnected: null,
    };
    
    const networkSlice = createSlice({
      name: 'network',
      initialState,
      reducers: {
        setIsConnected(state, action: PayloadAction<boolean>) {
          state.isConnected = action.payload;
        },
      },
    });
    
    export const { setIsConnected } = networkSlice.actions;
    export default networkSlice.reducer;
    

    src/slices/offlineQueueSlice.ts

    A simple queue for pending mutations.

    import { createSlice, PayloadAction } from '@reduxjs/toolkit';
    
    type QueuedMutation = {
      endpointName: string;
      args: any;
      extraOptions?: any;
    };
    
    type OfflineQueueState = {
      queue: QueuedMutation[];
    };
    
    const initialState: OfflineQueueState = {
      queue: [],
    };
    
    const offlineQueueSlice = createSlice({
      name: 'offlineQueue',
      initialState,
      reducers: {
        queueMutation(state, action: PayloadAction<QueuedMutation>) {
          state.queue.push(action.payload);
        },
        dequeueMutation(state) {
          state.queue.shift();
        },
        clearQueue(state) {
          state.queue = [];
        },
      },
    });
    
    export const { queueMutation, dequeueMutation, clearQueue } =
      offlineQueueSlice.actions;
    export default offlineQueueSlice.reducer;
    

    src/hooks/useNetworkStatus.ts

    Subscribes to NetInfo, updates Redux, and flushes the mutation queue when online.

    import { useEffect } from 'react';
    import NetInfo from '@react-native-community/netinfo';
    import { useAppDispatch, useAppSelector } from './useRedux';
    import { setIsConnected } from '../slices/networkSlice';
    import { api } from '../services/api';
    import { dequeueMutation } from '../slices/offlineQueueSlice';
    
    export const useNetworkStatus = () => {
      const dispatch = useAppDispatch();
      const isConnected = useAppSelector(state => state.network.isConnected);
      const queue = useAppSelector(state => state.offlineQueue.queue);
    
      // Subscribe to connectivity changes
      useEffect(() => {
        const unsub = NetInfo.addEventListener(state => {
          dispatch(setIsConnected(Boolean(state.isConnected)));
        });
        return unsub;
      }, [dispatch]);
    
      // Flush queued mutations when we go online
      useEffect(() => {
        if (isConnected && queue.length > 0) {
          // Replay all queued mutations in order
          queue.forEach(item => {
            dispatch(api.endpoints[item.endpointName].initiate(item.args, item.extraOptions));
            dispatch(dequeueMutation());
          });
        }
      }, [isConnected, queue, dispatch]);
    
      return isConnected;
    };
    

    src/hooks/useRedux.ts

    Typed hooks for convenience.

    import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
    import type { AppDispatch, RootState } from '../store';
    
    export const useAppDispatch = () => useDispatch<AppDispatch>();
    export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
    

    App.tsx

    Wraps the app with Provider/PersistGate and activates the connectivity hook.

    import React from 'react';
    import { View, Text, Button, FlatList } from 'react-native';
    import { Provider } from 'react-redux';
    import { PersistGate } from 'redux-persist/integration/react';
    import { store, persistor } from './src/store';
    import { useNetworkStatus } from './src/hooks/useNetworkStatus';
    import {
      useAddTodoMutation,
      useGetTodosQuery,
    } from './src/services/api';
    
    const Main = () => {
      // Start listening to connectivity and queue flushing
      const isConnected = useNetworkStatus();
    
      const { data: todos = [], isFetching } = useGetTodosQuery();
      const [addTodo, { isLoading: isAdding, error: addError }] =
        useAddTodoMutation();
    
      const handleAdd = async () => {
        await addTodo({ title: `New todo ${Date.now()}` });
      };
    
      return (
        <View style={{ flex: 1, padding: 16 }}>
          <Text>Network: {isConnected ? 'Online' : 'Offline'}</Text>
          <Button title="Add Todo" onPress={handleAdd} disabled={isAdding} />
          {addError ? <Text>Queued (offline) or failed</Text> : null}
          {isFetching ? (
            <Text>Loading...</Text>
          ) : (
            <FlatList
              data={todos}
              keyExtractor={item => String(item.id)}
              renderItem={({ item }) => <Text>{item.title}</Text>}
            />
          )}
        </View>
      );
    };
    
    export default function App() {
      return (
        <Provider store={store}>
          <PersistGate persistor={persistor} loading={null}>
            <Main />
          </PersistGate>
        </Provider>
      );
    }
    

    Notes

    • Install dependencies:
      yarn add @reduxjs/toolkit react-redux redux-persist @react-native-async-storage/async-storage @react-native-community/netinfo
    • The queueing logic above is intentionally minimal. In a production app you may want to:
      • Handle retries/backoff and de-duplication.
      • Provide optimistic updates for offline mutations.
      • Persist network slice if you prefer to remember last status.
      • Add stronger typing for args/extraOptions in the queue.

    This setup gives you a starting point for an offline-first RTK Query app with persisted state and automatic replay of queued mutations when connectivity is restored.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.