Home > Software engineering >  TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')
TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')

Time:05-01

Every time I press the favorites button it gives me an error.

TypeError: undefined is not an object  (evaluating 'state.favoriteBooks.findIndex')

This error occurs in the book.js redux reducer:

import { SET_BOOKS, TOGGLE_FAVORITE } from '../actions/types';

import Book from '../../models/book';

const initialState = {
  books: [],
  favoriteBooks: [],
};

export default (state = initialState, action) => {
  switch (action.type) {
 
case SET_BOOKS:
  return {
    books: action.books,
  };

    case TOGGLE_FAVORITE:
      const existingIndex = state.favoriteBooks.findIndex(
        (book) => book.id === action.bookId
      );
      if (existingIndex >= 0) {
        const updatedFavBooks = [...state.favoriteBooks];
        updatedFavBooks.splice(existingIndex, 1);
        return { ...state, favoriteBooks: updatedFavBooks };
      } else {
        const book = state.books.find((book) => book.id === action.bookId);
        return { ...state, favoriteBooks: state.favoriteBooks.concat(book) };
      }

    default:
      return state;
  }
};

I think the problem is that it's trying to find the index when the variable is empty. But when I run the dispatch toggleFavorite(BookId) it's putting in the book id.

CodePudding user response:

On SET_BOOKS return I forgot to add ..state.

 ...
    case SET_BOOKS:
  return {
    ...state,
    books: action.books,
  };
...

Don't forget to add ...state because you want to save previous states in initialState. That's why it didn't pick up any ids in books.

  • Related