rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 863 forks source link

How to store action for online? #1353

Closed David-Kristek closed 1 year ago

David-Kristek commented 2 years ago

I am developing mobile app with react-native, redux toolkit, redux-persist and I need an advice for folowing scenerio. The app basically stores todo tasks between group of people, and they can create them, delete them ...

Now I am facing this problem: If the user is offline, he can`t do anything with the data stored on server in database. And I would like to store that action and just keep it for the moment that he will be online again and then dispatch it - send the request to server.

Here is the example of actions in createApi :

export const taskApi = createApi({
  reducerPath: "taskApi",
  baseQuery: fetchBaseQuery({
    baseUrl: API,
    prepareHeaders: (headers, { getState }) => {
      if ((getState() as RootState).auth.logged) {
        const token = (getState() as RootState).auth.user?.token;
        headers.set("token", token ?? "");
      }
      return headers;
    },
  }),
  endpoints: (builder) => ({
    getTasks: builder.query<Task[], any>({ query: () => "" }),
    addTask: builder.mutation<any, Task>({
      query(body) {
        return { url: "", method: "post", body };
      },
    }),
    deleteTask: builder.mutation<any, string>({
      query(id) {
        console.log(id);
        return { url: `?id=${id}`, method: "delete"};
      },
    }),
    getTimeTableData: builder.query<TimeTable[][], void>({
      query() {
        return { url: "timetable", method: "get" };
      },
    }),
  }),
});

And in extraReducers in createSlice I have :

  .addMatcher(taskApi.endpoints.addTask.matchPending, (state, action) => {
    console.log("addTask pending");
    const newTask = action.meta.arg.originalArgs;
    state.tasks = state.tasks ? [...state.tasks, newTask] : [newTask];
  })

-I add the task to frontend while pending so it`s faster I would be glad for any answer or hint, thanks very much for help 🧑‍💻.