Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redux and API #4

Merged
merged 8 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.4.0",
"big.js": "^6.2.1",
"nanoid": "^4.0.2",
"prop-types": "^15.8.1",
Expand Down
8 changes: 8 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import { Books, Categories } from './Routes';
import 'react-toastify/dist/ReactToastify.css';
import { fetchBooks } from './redux/book/bookSlice';

function App() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchBooks());
});

return (
<BrowserRouter>
<Routes>
Expand Down
5 changes: 2 additions & 3 deletions src/components/Book.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
import React from 'react';
import PropTypes from 'prop-types';
import { useDispatch } from 'react-redux';
import { RemoveBook } from '../redux/book/bookSlice';
import { removeBook } from '../redux/book/bookSlice';

const Book = ({ id, title, author }) => {
const dispatch = useDispatch();

const handleRemove = (id) => {
dispatch(RemoveBook(id));
dispatch(removeBook(id));
};

return (
Expand Down
32 changes: 30 additions & 2 deletions src/components/Books.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,40 @@ import Book from './Book';
import Form from './Form';

const Books = () => {
const { books } = useSelector((state) => state.book);
const {
books, isLoading, isError, error,
} = useSelector(
(state) => state.book,
);

if (isLoading) {
return (
<>
<h1>LOADING BOOKS...</h1>
</>
);
}

if (isError) {
return (
<>
<h1>
Error occured!
{error}
</h1>
</>
);
}

return (
<div>
{books.map((book) => (
<Book key={book.item_id} id={book.item_id} title={book.title} author={book.author} />
<Book
key={book.id}
id={book.id}
title={book.title}
author={book.author}
/>
))}
<Form />
</div>
Expand Down
19 changes: 11 additions & 8 deletions src/components/Form.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useDispatch } from 'react-redux';
import { toast } from 'react-toastify';
import { AddBook } from '../redux/book/bookSlice';
import { nanoid } from 'nanoid';
import { addBook } from '../redux/book/bookSlice';

const Form = () => {
const { books } = useSelector((state) => state.book);
const dispatch = useDispatch();
const [author, setAuthor] = useState('');
const [title, setTitle] = useState('');
Expand All @@ -17,12 +17,12 @@ const Form = () => {
}

dispatch(
AddBook({
item_id: `item${books.length + 1}`,
addBook({
item_id: nanoid(),
author,
title,
category: 'unknown',
}),

);
setAuthor('');
setTitle('');
Expand All @@ -31,7 +31,7 @@ const Form = () => {
};

return (
<form className="flex flex-col gap-2" onSubmit={handleSubmit}>
<form className="flex flex-col gap-2" onSubmit={(e) => handleSubmit(e)}>
<h3>ADD NEW BOOK</h3>
<input
type="text"
Expand All @@ -47,7 +47,10 @@ const Form = () => {
value={author}
onChange={(e) => setAuthor(e.target.value)}
/>
<button type="submit" className="px-3 py-1 bg-blue-700 text-white mx-4 rounded-md">
<button
type="submit"
className="px-3 py-1 bg-blue-700 text-white mx-4 rounded-md"
>
Add book
</button>
</form>
Expand Down
15 changes: 15 additions & 0 deletions src/helpers/convertData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function convertData(data) {
const keys = Object.keys(data);
const result = keys.map((id) => {
const bookData = data[id][0];
return {
id,
author: bookData.author,
title: bookData.title,
category: bookData.category,
};
});
return result;
}

export default convertData;
167 changes: 124 additions & 43 deletions src/redux/book/bookSlice.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,132 @@
import { createReducer } from '@reduxjs/toolkit';
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import BASE_URL from '../../server';
import convertData from '../../helpers/convertData';
// fetch actions
export const fetchBooks = createAsyncThunk('books/getBooks', async () => {
try {
const response = await axios.get(`${BASE_URL}/books`);
return response.data;
} catch (error) {
const errorMessage = error.response
? error.response.data.error.message
: error.message;
return errorMessage;
}
});

export const addBook = createAsyncThunk('books/addBook', async (book) => {
try {
const response = await axios.post(`${BASE_URL}/books`, book);
if (!response.data) {
throw new Error('Error occured! Try again');
}
return book;
} catch (error) {
const errorMessage = error.response
? error.response.data.message
: error.message;
return errorMessage;
}
});

export const removeBook = createAsyncThunk('books/removeBook', async (id) => {
try {
const response = await axios.delete(`${BASE_URL}/books/${id}`);
if (!response.data) {
throw new Error('Error occured! Try again');
}
return id;
} catch (error) {
const errorMessage = error.response
? error.response.data.message
: error.message;
return errorMessage;
}
});

const initialState = {
books: [
{
item_id: 'item1',
title: 'The Great Gatsby',
author: 'John Smith',
category: 'Fiction',
},
{
item_id: 'item2',
title: 'Anna Karenina',
author: 'Leo Tolstoy',
category: 'Fiction',
},
{
item_id: 'item3',
title: 'The Selfish Gene',
author: 'Richard Dawkins',
category: 'Nonfiction',
},
],
books: [],
isLoading: false,
isSuccess: false,
isError: false,
error: null,
adding: false,
addedSuccess: false,
addedError: null,
deleting: false,
deletedSuccess: false,
deletedError: null,
};

// Reducers
export const bookReducer = createReducer(initialState, {
add: (state, action) => {
state.books.push(action.payload);
const bookSlice = createSlice({
name: 'book',
initialState,
reducers: {
add: (state, action) => {
state.books.push(action.payload);
},
remove: (state, action) => {
const id = action.payload;
const newState = state.books.filter((i) => i.item_id !== id);
state.books = newState;
},
},
remove: (state, action) => {
const id = action.payload;
const newState = state.books.filter((i) => i.item_id !== id);
state.books = newState;
extraReducers: (builder) => {
builder
.addCase(fetchBooks.pending, (state) => {
state.isLoading = true;
state.isError = false;
state.error = null;
})
.addCase(fetchBooks.fulfilled, (state, action) => {
const data = convertData(action.payload);
state.books = data;
state.isSuccess = true;
state.isLoading = false;
state.isError = false;
state.error = null;
})
.addCase(fetchBooks.rejected, (state, action) => {
state.isSuccess = false;
state.isLoading = false;
state.isError = true;
state.error = action.payload;
})
.addCase(addBook.pending, (state) => {
state.adding = true;
state.addedError = null;
state.addedSuccess = false;
})
.addCase(addBook.fulfilled, (state, action) => {
state.books = [...state.books, action.payload];
state.adding = false;
state.addedError = null;
state.addedSuccess = true;
})
.addCase(addBook.rejected, (state, action) => {
state.adding = false;
state.addedError = action.payload;
state.addedSuccess = false;
})
.addCase(removeBook.pending, (state) => {
state.deleting = true;
state.deletedSuccess = false;
state.deletedError = null;
})
.addCase(removeBook.fulfilled, (state, action) => {
state.books = state.books.filter((i) => i.id !== action.payload);
state.deleting = false;
state.deletedSuccess = true;
state.deletedError = null;
})
.addCase(removeBook.rejected, (state, action) => {
state.deleting = false;
state.deletedSuccess = false;
state.deletedError = action.payload;
});
},
});

// Actions
export const AddBook = (book) => (dispatch) => {
dispatch({
type: 'add',
payload: book,
});
};

export const RemoveBook = (id) => (dispatch) => {
dispatch({
type: 'remove',
payload: id,
});
};
// Reducer
export const bookReducer = bookSlice.reducer;
2 changes: 2 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const BASR_URL = 'https://us-central1-bookstore-api-e63c8.cloudfunctions.net/bookstoreApi/apps/zYRwMIbNeSNiqoe5qNWe';
export default BASR_URL;