Skip to content

Instantly share code, notes, and snippets.

@andrew-meads
Created May 8, 2025 05:21
Show Gist options
  • Save andrew-meads/181d6faf904226dc33f7c3155514db58 to your computer and use it in GitHub Desktop.
Save andrew-meads/181d6faf904226dc33f7c3155514db58 to your computer and use it in GitHub Desktop.
WDCC React worskhop, step 07 - Completing the Edit and Delete functions
const BASE_URL = import.meta.env.VITE_API_BASE_URL;
/**
* Sends a POST request to the server to create a new contact.
*
* @param {*} contact the new contact
*
* @returns a promise which will either resolve to the new contact object returned by the server,
* or will reject with the response object if a response outside the 200-299 range is returned.
*/
export async function createContact(contact) {
const response = await fetch(BASE_URL, {
method: "POST",
body: JSON.stringify(contact),
headers: { "content-type": "application/json" }
});
if (response.ok) return await response.json();
throw { response };
}
/**
* Sends a GET request to the server to get all contacts.
*
* @returns a promise which will resolve to an array of all contact info on the server.
*/
export async function retrieveContacts() {
const response = await fetch(BASE_URL);
return await response.json();
}
/**
* Sends a PATCH request to the server to update a contact.
*
* @param {*} contact the contact to update
*
* @returns a promise which will either resolve if the update was successful, or reject with the
* response object if a response object outside the 200-299 range is returned.
*/
export async function updateContact(contact) {
console.log("apiUpdateContact", contact);
const response = await fetch(`${BASE_URL}/${contact._id}`, {
method: "PATCH",
body: JSON.stringify(contact),
headers: { "content-type": "application/json" }
});
if (!response.ok) throw { response };
}
/**
* Sends a DELETE request to the server to delete a contact.
*
* @param {string} id the id of the contact to delete
*
* @returns a promise which will either resolve if the deletion was successful, or reject with the
* response object if a response object outside the 200-299 range is returned.
*/
export async function deleteContact(id) {
const response = await fetch(`${BASE_URL}/${id}`, {
method: "DELETE"
});
if (!response.ok) throw { response };
}
import { useContext, createContext, useState, useEffect } from "react";
import * as api from "../api/api.js";
const ContactsContext = createContext();
export function useContacts() {
return useContext(ContactsContext);
}
export default function ContactsContextProvider({ children }) {
const [contacts, setContacts] = useState([]);
const [selectedContact, setSelectedContact] = useState(null);
// Fetch contacts from server
async function fetchContacts() {
const data = await api.retrieveContacts();
setContacts(data);
setSelectedContact(data[0]);
}
// TODO On initial page mount, fetch contacts.
useEffect(() => {
fetchContacts();
}, []);
// TODO Function for adding a new contact
// Function for deleting a contact
async function deleteContact(id) {
console.log("Deleting contact with id:", id);
try {
await api.deleteContact(id);
setContacts((prevContacts) => prevContacts.filter((contact) => contact._id !== id));
setSelectedContact(null); // Deselect the contact after deletion
} catch (err) {
// TODO Proper error handling
console.error("Error deleting contact:", err.response.status);
}
}
// Function for editing a contact
async function editContact(contact) {
console.log("Editing contact:", contact);
try {
await api.updateContact(contact);
setContacts((prevContacts) =>
prevContacts.map((c) => (c._id === contact._id ? { ...c, ...contact } : c))
);
if (selectedContact && selectedContact._id === contact._id) {
setSelectedContact({ ...selectedContact, ...contact });
}
} catch (err) {
// TODO Proper error handling
console.error("Error editing contact:", err.response.status);
}
}
const context = {
contacts,
selectedContact,
setSelectedContact,
deleteContact,
editContact
};
return <ContactsContext.Provider value={context}>{children}</ContactsContext.Provider>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment