State lot of items in Redux toolkit with api response

Viewed 27

I m coding a bookmark list for users. I want to stock the api response in an array. I m using Google Book Api. I m using Redux Toolkit.

User can add books in his personal wishlist and to display and made some operations I need to stock in state books informations added.

For the moment I have only 1 book stock cause if I try to add another one in state, this one changes with the new one only. I need to stock all books added.

Any ideas ?

bookSlice.js

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { BOOKS_BY_ID } from "../../services/api/googleBooks";

export const getBook = createAsyncThunk(
    "book/getBook",
    async ({ bookid }) => {
        const response = await fetch(`${BOOKS_BY_ID}${bookid}`);
        const data = await response.json();
        return data;
    }
);


const bookSlice = createSlice({
    name: "book",
    initialState: {
        list: [],
        status: null,
    },
    reducers: {},
    extraReducers: {
        [getBook.pending]: (state, action) => {
            state.status = "loading";
        },
        [getBook.fulfilled]: (state, action) => {
            state.status = "success";
            state.list = action.payload;
        },
        [getBook.rejected]: (state, action) => {
            state.status = "failed";
        },
    },
});

export default bookSlice.reducer;

FetchBookBookmarked.js

useEffect(() => {
    // let allBook = [];
    let ignore = false;
    bookInfos?.map(async (book) => {
      dispatch(getBook({ bookid: book }));

      
      await axios.get(`${BOOKS_BY_ID}${book}`).then((res) => {
        // allBook.push(res.data);
        if (!ignore) {
          setBookDetail((oldValues) => [...oldValues, res.data]);
        }
      });
    });
    return () => {
      ignore = true;
    };
  }, [bookInfos, dispatch]);
1 Answers

Push the book data into the list.

Replace following line:

state.list = action.payload;

To:

state.list.push(action.payload)

To avoid duplicates, you can check the ID before adding it:

const bookAlreadyExists = state.list.some(book => book.id === action.payload.id)
if (!bookAlreadyExists) {
  state.list.push(action.payload)
}
Related