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

Connecting API #5

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
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
5 changes: 5 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 @@ -15,6 +15,7 @@
"react-scripts": "5.0.1",
"redux": "^4.2.0",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.4.1",
"uuid": "^8.3.2",
"web-vitals": "^2.1.4"
},
Expand Down
45 changes: 37 additions & 8 deletions src/components/AddNewBook.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,45 @@
import React, { useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { useDispatch } from 'react-redux';
import { addBook } from '../redux/Books/books';
import { v4 as uuidv4 } from 'uuid';
import { postBook } from '../redux/Books/books';

const AddNewBook = () => {
const [inputValues, setInputValues] = useState({
booktitle: '',
title: '',
author: '',
id: '',
category: '',
});
const dispatch = useDispatch();
const [errorMsg, setError] = useState('');

const submitBookToStore = (e) => {
e.preventDefault();
const id = uuidv4();
const { booktitle, category } = inputValues;
const { title, author, category } = inputValues;
const newBook = {
booktitle,
id,
title,
author,
category,
};
dispatch(addBook(newBook));

if (newBook.title.trim().length === 0) {
setError('Please add Book title to submit...');
setInputValues(newBook);
} else if (newBook.category === '') {
setError('Please select Book Category to submit...');
setInputValues(newBook);
} else {
setError('');
dispatch(postBook(newBook));
setInputValues({
title: '',
author: '',
id: '',
category: '',
});
}
};

const onChange = (e) => {
Expand All @@ -35,18 +55,27 @@ const AddNewBook = () => {
<input
type="text"
placeholder="Book title"
name="booktitle"
name="title"
onChange={onChange}
required
/>

<input
type="text"
placeholder="Book author"
name="author"
onChange={onChange}
required
/>
<select placeholder="categories" name="category" onChange={onChange} required>
<option>Category</option>
<option value="">Category</option>
<option value="Romance">Romance</option>
<option value="Documentary">Documentary</option>
<option value="Fiction">Fiction</option>
<option value="Crime">Crime</option>
</select>
<button type="submit" onClick={submitBookToStore}>Add Book</button>
<small>{errorMsg}</small>
</form>
);
};
Expand Down
9 changes: 8 additions & 1 deletion src/components/BookItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { removeBook } from '../redux/Books/books';

const BookItem = ({ book }) => {
const {
booktitle, id, category,
booktitle, id, author, category,
} = book;
const dispatch = useDispatch();

Expand All @@ -16,6 +16,12 @@ const BookItem = ({ book }) => {
{' '}
{ booktitle }
</p>
<p>
Author:
{' '}
{ author }
</p>

<p>
Category:
{' '}
Expand All @@ -31,6 +37,7 @@ BookItem.propTypes = {
{
booktitle: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
author: PropTypes.string.isRequired,
category: PropTypes.string.isRequired,
},
).isRequired,
Expand Down
34 changes: 19 additions & 15 deletions src/components/Books.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import React from 'react';
import PropTypes from 'prop-types';
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getBooksList } from '../redux/Books/books';
import BookItem from './BookItem';

const Books = ({ bookList }) => (
<ul className="books-list-section">
{bookList.map((book) => (
<BookItem key={book.id} book={book} />
))}
</ul>
);
const Books = () => {
const dispatch = useDispatch();
const booksList = useSelector((state) => state.booksReducer);

Books.propTypes = {
bookList: PropTypes.arrayOf(PropTypes.shape(
{
id: PropTypes.string.isRequired,
},
)).isRequired,
useEffect(() => {
dispatch(getBooksList());
}, [dispatch]);

return (
<ul className="books-list-section">
{booksList
? booksList.map((book) => (
<BookItem key={book.id} book={book} />
))
: 'Loading...'}
</ul>
);
};

export default Books;
18 changes: 13 additions & 5 deletions src/components/CategoryPage.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { checkStatus } from '../redux/Categories/categories';

const CategoryPage = () => (
<div>
<h1>Under construction!!</h1>
</div>
);
const CategoryPage = () => {
const Category = useSelector((state) => state.categoryReducer);
const dispatch = useDispatch();
const handleClick = () => dispatch(checkStatus());
return (
<div>
<button onClick={handleClick} type="button"> Check status</button>
<h1>{Category}</h1>
</div>
);
};

export default CategoryPage;
2 changes: 1 addition & 1 deletion src/index.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
body {
background-color: white;
background-color: aqua;
}
56 changes: 55 additions & 1 deletion src/redux/Books/books.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Redux
// import axios from 'axios';

const ADD_BOOK = 'bookStore/books/ADD_BOOK';
const REMOVE_BOOK = 'bookStore/books/REMOVE_BOOK';
const GET_BOOKS = 'bookStore/books/GET_BOOKS';
const baseURL = 'https://us-central1-bookstore-api-e63c8.cloudfunctions.net/bookstoreApi/apps/Z2vqZCN1ojOLzLMr9F63/books';

const initialState = [];

Expand All @@ -9,6 +12,11 @@ export const addBook = (payload) => ({
payload,
});

export const getBooks = (payload) => ({
type: GET_BOOKS,
payload,
});

export const removeBook = (payload) => ({
type: REMOVE_BOOK,
payload,
Expand All @@ -22,9 +30,55 @@ const booksReducer = (state = initialState, action) => {
case REMOVE_BOOK:
return state.filter((book) => book.id !== action.payload);

case GET_BOOKS:
return action.payload;

default:
return state;
}
};

export const getBooksList = () => async (dispatch) => {
const booksList = await fetch(`${baseURL}`)
.then((response) => response.json());
const booksID = Object.keys(booksList);
const formatedBooks = [];
booksID.map((key) => formatedBooks.push({
id: key,
title: booksList[key][0].title,
author: booksList[key][0].author,
category: booksList[key][0].category,
}));
dispatch(getBooks(formatedBooks));
};

export const postBook = (newBook) => async (dispatch) => {
await fetch(`${baseURL}`, {
method: 'POST',
body: JSON.stringify({
item_id: newBook.id,
title: newBook.title,
author: newBook.author,
category: newBook.category,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
dispatch(addBook(newBook));
};

export const deleteBook = (id) => async (dispatch) => {
await fetch(`${baseURL}/${id}`, {
method: 'DELETE',
body: JSON.stringify({
item_id: id,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
dispatch(removeBook(id));
};

export default booksReducer;
2 changes: 1 addition & 1 deletion src/redux/Categories/categories.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Redux
const CHECK_STATUS = 'bookStore/categories/CHECK_STATUS';
const CHECK_STATUS = 'CHECK_STATUS';

const initialState = [];

Expand Down
5 changes: 2 additions & 3 deletions src/redux/configureStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@

import { createStore, combineReducers, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import booksReducer from './Books/books';
import categoryReducer from './Categories/categories';

const reducer = combineReducers({
booksReducer,
categoryReducer,
// additional reducers could be added here
});

const store = createStore(
reducer,
applyMiddleware(logger),
applyMiddleware(logger, thunk),
);

export default store;