Skip to content

Commit

Permalink
feat: error handling in API
Browse files Browse the repository at this point in the history
  • Loading branch information
Param-Harrison committed Apr 21, 2020
1 parent 6a6532e commit 5e01445
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
20 changes: 14 additions & 6 deletions src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ export const postContacts = async (payload) => {
};

export const putContacts = async ({ id, ...payload }) => {
const response = await fetch(`${BASE_URL}/contacts/${id}`, {
method: "PUT",
...requestPayload(payload),
});
const data = await response.json();
return data;
try {
const response = await fetch(`${BASE_URL}/contacts/${id}`, {
method: "PUT",
...requestPayload(payload),
});
if (response.ok) {
const data = await response.json();
return { data };
} else {
throw Error(response.statusText);
}
} catch (error) {
return { error };
}
};

export const deleteContacts = async (id) => {
Expand Down
22 changes: 16 additions & 6 deletions src/components/edit-contact.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import ContactForm from "./contact-form";
import { useGlobalStore } from "./global-state";
Expand All @@ -8,17 +8,27 @@ const EditContact = (props) => {
const id = props.match.params.id;
const history = useHistory();
const { editContact } = useGlobalStore();
const [error, setError] = useState("");

const onSubmit = (submitData) => {
const payload = { id, ...submitData };
const payload = { ...submitData };
(async () => {
const data = await putContacts(payload);
editContact(data);
history.push("/");
const { data, error } = await putContacts(payload);
if (error) {
setError(error.message);
} else {
editContact(data);
history.push("/");
}
})();
};

return <ContactForm id={id} title={"Edit contact"} onSubmit={onSubmit} />;
return (
<>
{error ? <div>{error}</div> : null}
<ContactForm id={id} title={"Edit contact"} onSubmit={onSubmit} />
</>
);
};

export default EditContact;

0 comments on commit 5e01445

Please sign in to comment.