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

Roland's latest version of DeliverEat #18

Open
wants to merge 27 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
e1686ad
First version with basic API being fetched and rendered
rolandjlevy Oct 11, 2018
daabc57
Form calculating orders
rolandjlevy Oct 12, 2018
38f6062
Working on orders
rolandjlevy Oct 12, 2018
a53152f
Shopping basket working
rolandjlevy Oct 12, 2018
104b80a
Working on displaying all orders
rolandjlevy Oct 12, 2018
3c7e0d6
All orders now being displayed
rolandjlevy Oct 12, 2018
76e21b0
Trying to debug error with keys in JSX in App.js
rolandjlevy Oct 13, 2018
235a862
Fixed bug: key wasn't being set in displayAllOrders() map
rolandjlevy Oct 13, 2018
59f3400
Working on form data
rolandjlevy Oct 13, 2018
c332ea4
Bug with getCurrency
rolandjlevy Oct 13, 2018
536ecef
Bug with getCurrecy fixed. New bug with adding form data
rolandjlevy Oct 13, 2018
a7873c0
Bug with getting form data
rolandjlevy Oct 13, 2018
89a89d9
Fixed bug with form data :)
rolandjlevy Oct 13, 2018
736dc5a
Form data being added to order with some validation
rolandjlevy Oct 13, 2018
7588215
Breaking down App into components
rolandjlevy Oct 14, 2018
b0b31d0
Changed <Menu> into a stateless component
rolandjlevy Oct 14, 2018
60bcc8d
Basket improved. Now filtering on all orders
rolandjlevy Oct 15, 2018
06c255d
small tweaks
rolandjlevy Oct 15, 2018
a5a060e
Tweaked SCSS
rolandjlevy Oct 15, 2018
79213b2
Tidied up some code - mainly unecessary binding
rolandjlevy Oct 15, 2018
f59dffa
Created MenuItem.js component
rolandjlevy Oct 15, 2018
9459585
Continuing on breaking up components
rolandjlevy Oct 15, 2018
ffbc191
Completed separated App.js into individual components
rolandjlevy Oct 15, 2018
9f373fd
Created tooltip functionality for each menu item so thumbnail appears…
rolandjlevy Oct 16, 2018
d5b91a4
Completed tooltips
rolandjlevy Oct 16, 2018
1b1e27d
Tweaked CSS for tooltips
rolandjlevy Oct 17, 2018
89e24e8
Updated structure of orders object
rolandjlevy Oct 17, 2018
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
80 changes: 80 additions & 0 deletions data/menu.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const menu = {
1: {
menuId: 1,
name: "Mixed Salad",
price: 6,
type: "starter",
image: "https://images.unsplash.com/photo-1523986371872-9d3ba2e2a389?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=b6afec6bcb9eeae00384f31cc31c7e58&auto=format&fit=crop&w=1500&q=80"
},
2: {
menuId: 2,
name: "Fried chicken",
price: 4,
type: "starter",
image: "https://images.unsplash.com/photo-1426869981800-95ebf51ce900?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=63ec77eae2b7b81c8beab9e87bbd3a01&auto=format&fit=crop&w=1500&q=80"
},
3: {
menuId: 3,
name: "Vegetable soup",
price: 3,
type: "starter",
image: "https://images.unsplash.com/photo-1455619452474-d2be8b1e70cd?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=74ac7c1aa35dc36f50cc1ac7517c70a7&auto=format&fit=crop&w=1500&q=80"
},
4: {
menuId: 4,
name: "Beef stew",
price: 7,
type: "main",
image: "https://images.unsplash.com/photo-1519699788450-ad34386a3bfc?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=e27d75234956ab719c61be2613dcfc69&auto=format&fit=crop&w=1500&q=80"
},
5: {
menuId: 5,
name: "Fish & chips",
price: 8,
type: "main",
image: "https://images.unsplash.com/photo-1524334788144-6dc88da21500?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=46507e188428bfb7dbe2413ab55af741&auto=format&fit=crop&w=1500&q=80"
},
6: {
menuId: 6,
name: "Pork chops & vegetables",
price: 3,
type: "main",
image: "https://images.unsplash.com/photo-1432139555190-58524dae6a55?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=549d2b7a71978de6e5320ba19fb4d21e&auto=format&fit=crop&w=1510&q=80"
},
7: {
menuId: 7,
name: "Blueberry cheesecake",
price: 2,
type: "dessert",
image: "https://images.unsplash.com/photo-1533134242443-d4fd215305ad?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8c57988ce931873edf1deaa6bf2cf705&auto=format&fit=crop&w=1350&q=80"
},
8: {
menuId: 8,
name: "Chocolate cake",
price: 3,
type: "dessert",
image: "https://images.unsplash.com/photo-1535911765168-1fafc87dcfa3?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=f27e057856c0f66d60aa333118348aa1&auto=format&fit=crop&w=1047&q=80"
},
9: {
menuId: 9,
name: "Trifle",
price: 4,
type: "dessert",
image: "https://images.unsplash.com/photo-1514424350208-755887f7b374?ixlib=rb-0.3.5&s=d9482c1db08ecb9766cc9c6b627ecc2e&auto=format&fit=crop&w=1050&q=80"
}
};

// function getMenuItems () {
// return Object.values(menu);
// }
// function getMenuItembyId (id) {
// return menu[id];
// }

// module.exports = {
// getMenuItems,
// getMenuItembyId
// }


exports.menu = menu;
14 changes: 14 additions & 0 deletions data/orders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
let orders = {};

function addToOrders (newOrder) {
const keys = Object.keys(orders);
const orderId = keys.length ? Math.max(...keys) + 1 : 1;
orders = Object.assign({}, orders, {[orderId]: newOrder});
}

function getOrders () {
return orders;
}

exports.addToOrders = addToOrders;
exports.getOrders = getOrders;
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"test": "jest",
"dev": "webpack --mode development",
"build": "webpack --mode production"
"build": "webpack --mode production",
"start": "nodemon server.js"
},
"author": "",
"license": "ISC",
Expand Down
55 changes: 44 additions & 11 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,56 @@

// SERVER: server.js is running on server with node
// BROWSER: react is running in the browser

// EXPLANATION AND ORDER OF EVENTS
// we start with node.js and run the server at port 8080
// type in URL
// server.js renders index.hbs file in 'views' folder, as defined in app.get()
// All files in express are stored in 'views' folder
// app.get is first the request - the route that deals with requests coming into the root path
// html is loaded into the browser and parsed
// app.use() external dependancies in the 'static' folder are loaded into the browser (styles.css and bundle.js)
// we create an API from the menu object in server.js and use fetch to load the menu into the browser

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
app.use('/static', express.static('static'));
app.set('view engine', 'hbs');
const { menu } = require('./data/menu.js');
const { addToOrders, getOrders } = require('./data/orders.js');

// let orders = {};

// bodyParser converts json into correct format
app.use(bodyParser.json());

// this is middleware - define where to look for static files / dependancies
app.use('/static', express.static('static'));

const menu = {
1: {
id: 1,
name: "Strawberry cheesecake",
price: 6
}
};
// server is using the handlebars (hbs) format to render html files
app.set('view engine', 'hbs');

// we are in the browser, at localhost:8080/
// when this first route is excecutes it renders index.hbs from 'views' folder
app.get('/', function(req, res){
res.render('index');
});

app.get('/api/menu', function (req, res) {
res.json(menu);
});

app.post('/api/order', function(req, res){
addToOrders(req.body);
res.status(200).json({message: "successful"});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IT would be better to return order object with id here so the API user can have a reference to the object that was created for later use

// res.status(404).json({error: 'Student not found'});
});

app.get('/api/order', function(req, res){
const result = getOrders();
res.json(result);
})

app.listen(8080, function(){
console.log('Listening on port 8080');
});
});
Binary file added src/assets/picture-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
188 changes: 183 additions & 5 deletions src/components/App.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,197 @@
import React from 'react';

import Menu from './Menu';
import OrdersDisplayed from './OrdersDisplayed';
import OrderCurrent from './OrderCurrent';
import '../styles/App.scss';
import '../styles/Form.scss';
import '../styles/Tooltip.scss';

class App extends React.Component {
constructor(){
super();

this.handleSubmit = this.handleSubmit.bind(this);
this.receiveHandleChange = this.receiveHandleChange.bind(this);
this.getCurrency = this.getCurrency.bind(this);
this.emptyBasket = this.emptyBasket.bind(this);
this.toggleBasket =this.toggleBasket.bind(this);
this.filterOrders = this.filterOrders.bind(this);
this.handleFormData = this.handleFormData.bind(this);
this.formatDate = this.formatDate.bind(this);

this.state = {
menu: {},
currentOrder: null,
orders: null,
basketVisible: null,
filterInput: null,
tooltip: "thumb"
}
}

/* get menu data
///////////////////////////////////////////*/

componentDidMount () {
fetch("/api/menu")
.then(response => response.json())
.then(menu => {
this.setState({ menu })
})
}

/* post current order from basket
///////////////////////////////////////////*/

handleSubmit (event) {
event.preventDefault();
fetch('/api/order', {
method: 'post',
body: JSON.stringify(this.state.currentOrder),
headers: { 'Content-Type': 'application/json' }
}
).then(response => response.json()
).then(order => {
this.fetchAllOrders();
});
}

handleFormData (event) {
const currentOrder = Object.assign({}, this.state.currentOrder, {[event.target.name]: event.target.value});
this.setState({ currentOrder });
}

/* get all orders
///////////////////////////////////////////*/

fetchAllOrders () {
fetch('/api/order')
.then(response => response.json())
.then(orders => {
this.setState({
orders: orders,
currentOrder: null
})
});
}

/* add item to basket for current order
///////////////////////////////////////////*/

receiveHandleChange (id, event) {
let currentOrder;
if (event.target.value === "0") {
currentOrder = Object.assign({}, this.state.currentOrder);
delete currentOrder[id];
} else {
currentOrder = Object.assign({}, this.state.currentOrder, { [id]: {"menuId": id, "quantity": Number(event.target.value) }, "date": this.formatDate()})
}
this.setState({ currentOrder });
}

/* display prices as GBPs
///////////////////////////////////////////*/

getCurrency (string) {
return string.toLocaleString("en-GB", {
style: "currency",
currency: "GBP"
});
}

formatDate (){
const date = new Date();
const addZero = n => n < 10 ? `0${n}` : n;
return `${addZero(date.getDate())}-${addZero(date.getMonth()+1)}-${date.getFullYear()}`;
}

filterOrders (event) {
this.setState({ filterInput: event.target.value });
}

/* control basket
///////////////////////////////////////////*/

emptyBasket (event) {
event && event.preventDefault();
this.setState({ currentOrder: null });
}

toggleBasket (event) {
event.preventDefault();
this.setState({ basketVisible: !this.state.basketVisible });
}

render(){

const currentOrderHasFood = this.state.currentOrder && Object.values(this.state.currentOrder).find(item => typeof item === "object");

const currentOrderComp =
(<OrderCurrent
currentOrder={this.state.currentOrder}
menu={this.state.menu}
emptyBasket={this.emptyBasket}
getCurrency={this.getCurrency}
/>)

const basket = this.state.basketVisible &&
(<div className="basket">
<h2>Your basket <i className="fas fa-1x fa-shopping-basket"></i></h2>
<div>{ currentOrderHasFood ? currentOrderComp : <div>Your basket is empty</div>}</div>
</div>)

const basketCount = this.state.currentOrder && (Object.values(this.state.currentOrder).filter(item => typeof item === "object").length || null);

const formElements = currentOrderHasFood && this.state.basketVisible &&
(<div className="form__elements">
<input onChange={this.handleFormData} name="username" value={this.state.currentOrder.username || ""} id="username" className="menu__form__username" type="text" placeholder="Full name"></input>
<input onChange={this.handleFormData} name="telephone" value={this.state.currentOrder.telephone || ""} id="telephone" className="menu__form__telephone" type="text" placeholder="Telephone number"></input>
{this.state.currentOrder.username && this.state.currentOrder.telephone &&
<button name="submit" id="submit" className="menu__form__submit" type="submit">Send order</button>
}
</div>)

const allOrders = this.state.orders &&
<OrdersDisplayed
filterInput={this.state.filterInput}
orders={this.state.orders}
menu={this.state.menu}
getCurrency={(price) => this.getCurrency(price)}
filterOrders={this.filterOrders}
/>

const menu = this.state.menu &&
<Menu
receiveHandleChange={(id, event) => this.receiveHandleChange(id, event)}
getCurrency={(price) => this.getCurrency(price)}
menu={this.state.menu}
currentOrder={this.state.currentOrder}
/>

return (
<div>
Delivereat app
</div>
<React.Fragment>

<div className="header">
<h1>DeliverEat <i className="fas fa-1x fa-utensils"></i></h1>
<div className="basket__menu"><h1 className="basket__items-count">{basketCount}</h1><h1><a href="#" onClick={this.toggleBasket}><i className="fas fa-1x fa-shopping-basket basket__display-toggle"></i></a></h1></div>
</div>

<div className="content">
<form onSubmit={this.handleSubmit} className="menu__form">

<div className="form__wrapper">
{ basket }
{ formElements }
</div>

{ allOrders }
{ menu }

</form>
</div>
</React.Fragment>
)
}
}

export default App;
export default App;
Loading