Skip to content

Commit

Permalink
fully functioning error handling on both client and serverside
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenespinal committed Oct 18, 2019
1 parent ea9aa54 commit 97e5eea
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 29 deletions.
8 changes: 4 additions & 4 deletions .idea/workspace.xml

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

27 changes: 16 additions & 11 deletions pages/api/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,23 @@ async function handleGetRequest(req, res) {

async function handlePostRequest(req, res) {
const {name, price, description, mediaUrl} = req.body;
if (!name || !price || !description || !mediaUrl) {
//422 status is when not enough information was provided
return res.status(422).send("Product is missing one or more fields");
}
const product = await new Product({
name,
price,
description,
mediaUrl
}).save();
try {
if (!name || !price || !description || !mediaUrl) {
//422 status is when not enough information was provided
return res.status(422).send("Product is missing one or more fields");
}
const product = await new Product({
name,
price,
description,
mediaUrl
}).save();
// resource created is a 201 request
res.status(201).json(product);
res.status(201).json(product);
} catch (error) {
console.error(error);
res.status(500).send("Server error in creating product")
}
}

async function handleDeleteRequest(req, res) {
Expand Down
55 changes: 41 additions & 14 deletions pages/create.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {Form, Input, TextArea, Button, Image, Message, Header, Icon} from 'semantic-ui-react';
import React, {Fragment, useState, Component} from 'react';
import React, {Fragment, useState, useEffect} from 'react';
import axios from 'axios';
import baseUrl from "../utils/baseUrl";
import catchErrors from '../utils/catchErrors';

const INITIAL_PRODUCT = {
name: "",
Expand All @@ -15,6 +16,20 @@ function CreateProduct() {
const [mediaPreview, setMediaPreview] = useState('');
const [success, setSuccess] = useState(false);
const [loading, setLoading] = useState(false);
const [disabled, setDisabled] = useState(true);
const [error, setError] = useState('');

useEffect(() => {
// Object.values() gives back the values within the object ES7 syntax
// .every loops through each element in product variable and converts
// it to a true or false boolean value. Each property cannot be null in order
// for it to return true. We then store that into isProduct variable
const isProduct = Object.values(product).every(el => Boolean(el));
// if isProduct is true? we setDisabled back to false since
// initially we stated it to be true
// otherwise it will remain true
isProduct ? setDisabled(false) : setDisabled(true);
}, [product]);

function handleChange(event) {
const {name, value, files} = event.target;
Expand All @@ -40,17 +55,24 @@ function CreateProduct() {
}

async function handleSubmit(event) {
event.preventDefault();
setLoading(true);
const mediaUrl = await handleImageUpload();
console.log(mediaUrl);
const url = `${baseUrl}/api/product`;
const payload = {...product, mediaUrl};
const response = await axios.post(url, payload);
console.log({response});
setLoading(false);
setProduct(INITIAL_PRODUCT);
setSuccess(true);
try {
event.preventDefault();
setLoading(true);
const mediaUrl = await handleImageUpload();
console.log(mediaUrl);
const url = `${baseUrl}/api/product`;
const payload = {...products, mediaUrl};
const response = await axios.post(url, payload);
console.log({response});
// setLoading(false);
setProduct(INITIAL_PRODUCT);
setSuccess(true);
} catch (error) {
catchErrors(error, setError);
// console.error(error);
} finally {
setLoading(false);
}
}

const {name, price, description} = product;
Expand All @@ -60,7 +82,12 @@ function CreateProduct() {
<Icon name="add" color="red"/>
Create New Product
</Header>
<Form loading={loading} success={success} onSubmit={handleSubmit}>
<Form loading={loading} error={Boolean(error)} success={success} onSubmit={handleSubmit}>
<Message
error
header="Oops!"
content={error}
/>
<Message
success
icon="check"
Expand Down Expand Up @@ -109,7 +136,7 @@ function CreateProduct() {
/>
<Form.Field
control={Button}
disabled={loading}
disabled={disabled || loading}
color="blue"
icon="pencil alternate"
type="submit"
Expand Down
28 changes: 28 additions & 0 deletions utils/catchErrors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
function catchErrors(error, displayError) {
let errorMsg;
const {response, request} = error;
if (response) {
//req was made and server responded with a status code that is not 2XX range
errorMsg = response.data;
console.error("Error response", errorMsg);

// For cloudinary image upload error
if (response.data.error) {
errorMsg = response.data.error.message;
}
} else if (request) {
// req was made but no response was returned
errorMsg = request;
console.error("Error Request", errorMsg);
} else {
// something else went wrong
errorMsg = message;
console.error("Error", errorMsg);
}

displayError(errorMsg);


}

export default catchErrors;

0 comments on commit 97e5eea

Please sign in to comment.