Skip to content

Commit

Permalink
Implement thunk in all actionCreators
Browse files Browse the repository at this point in the history
  • Loading branch information
TadesseDev committed May 4, 2022
1 parent b3d1f70 commit 8632b11
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions src/redux/books/books.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
import { v4 as uuidv4 } from 'uuid';
import { getBooksAPI, addBookAPI, removeBookAPI } from '../../API/app';

const ADD_BOOK = 'NEW_BOOK_ADD';
const REMOVE_BOOK = 'BOOK_REMOVED';
const initialState = [
{
id: uuidv4(),
title: 'The Hunger Game',
author: 'Suzanne Collins',
},
{
id: uuidv4(),
title: 'The Hunger Game',
author: 'Suzanne Collins',
},
];
const initialState = [];

export const addBook = (title, author) => (
{ type: ADD_BOOK, payload: { title, author, id: uuidv4() } }
);
export const removeBook = (id) => ({ type: REMOVE_BOOK, payload: id });
export const getBooksFromServer = () => async (dispatch) => {
const data = await getBooksAPI();
const result = Object.entries(data).map((data) => {
let [, res] = data;
[res] = res;
[res.id] = data;
return (res);
});
dispatch(({ type: ADD_BOOK, payload: result }));
};

export const addBook = (title, author) => (dispatch) => {
const book = {
id: uuidv4(), title, author, category: 'not set',
};
addBookAPI(book).then(() => {
dispatch({ type: ADD_BOOK, payload: [book] });
});
};
export const removeBook = (id) => (dispatch) => {
removeBookAPI(id).then(() => {
dispatch({ type: REMOVE_BOOK, payload: id });
});
};

export default (state = initialState, action) => {
switch (action.type) {
case ADD_BOOK:
return [
...state,
action.payload,
...action.payload,
];
case REMOVE_BOOK:
return state.filter((book) => (book.id !== action.payload ? book : false));
Expand Down

0 comments on commit 8632b11

Please sign in to comment.