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

Bookstore: connect to API #4

Merged
merged 12 commits into from May 4, 2022
15 changes: 15 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
Expand Up @@ -13,6 +13,7 @@
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"redux": "^4.2.0",
"redux-thunk": "^2.4.1",
"uuid": "^8.3.2",
"web-vitals": "^2.1.4"
},
Expand Down
47 changes: 47 additions & 0 deletions src/API/app.js
@@ -0,0 +1,47 @@
const appId = 'ZijPZapn481OKArMG39M';
const baseUrl = `https://us-central1-bookstore-api-e63c8.cloudfunctions.net/bookstoreApi/apps/${appId}/books`;
const bookString = (book) => JSON.stringify({
item_id: book.id,
title: book.title,
author: book.author,
category: book.category,
});

export const getBooksAPI = async () => {
try {
const result = await fetch(baseUrl);
const data = await result.json();
return data;
} catch (error) {
return error;
}
};

export const addBookAPI = async (book) => {
try {
await fetch(baseUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: bookString(book),
});
return true;
} catch (error) {
return false;
}
};

export const removeBookAPI = async (id) => {
const url = `${baseUrl}/${id}`;
try {
const result = await fetch(url, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ item_id: id }),
});
return result;
} catch (error) {
return error;
}
};
9 changes: 7 additions & 2 deletions src/components/Books.js
@@ -1,10 +1,15 @@
import React from 'react';
import { useSelector } from 'react-redux';
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Book from './sub-components/book';
import AddNewBook from './sub-components/AddNewBook';
import { getBooksFromServer } from '../redux/books/books';

export default function Books() {
const dispatch = useDispatch();
const books = useSelector((store) => store.books);
useEffect(() => {
dispatch(getBooksFromServer());
}, []);
return (
<div>
{books.map((book) => (
Expand Down
12 changes: 7 additions & 5 deletions src/components/sub-components/AddNewBook.js
Expand Up @@ -6,15 +6,17 @@ export default function AddNewBook() {
const dispatch = useDispatch();
const handleNewBookSubmit = (event) => {
event.preventDefault();
const title = event.target.elements[0].value;
const author = event.target.elements[1].value;
dispatch(addBook(title, author));
const title = event.target.elements[0];
const author = event.target.elements[1];
dispatch(addBook(title.value, author.value));
title.value = '';
author.value = '';
};
return (
<div id="add-new-book">
<form action="#" method="POST" onSubmit={handleNewBookSubmit}>
<input type="text" name="title" id="title" placeholder="Book Title" />
<input type="text" name="author" id="author" placeholder="Book author" />
<input type="text" name="title" id="title" placeholder="Book Title" required />
<input type="text" name="author" id="author" placeholder="Book author" required />
<button type="submit">Add Book</button>
</form>
</div>
Expand Down
20 changes: 9 additions & 11 deletions src/index.js
Expand Up @@ -9,15 +9,13 @@ import store from './redux/configureStore';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Books />} />
<Route path="/categories" element={<Categories />} />
</Routes>
</BrowserRouter>
</Provider>
</React.StrictMode>,
<Provider store={store}>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Books />} />
<Route path="/categories" element={<Categories />} />
</Routes>
</BrowserRouter>
</Provider>,
);
44 changes: 27 additions & 17 deletions src/redux/books/books.js
@@ -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
5 changes: 3 additions & 2 deletions src/redux/configureStore.js
@@ -1,4 +1,5 @@
import { createStore, combineReducers } from 'redux';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import books from './books/books';
import categories from './categories/categories';

Expand All @@ -7,6 +8,6 @@ const rootReducer = combineReducers({
categories,
});

const store = createStore(rootReducer);
const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;