Skip to content

Commit

Permalink
πŸ€ Refactored Resources API Call (#996)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hemu21 authored Jun 3, 2024
1 parent aae2a33 commit ae4168f
Show file tree
Hide file tree
Showing 3 changed files with 156 additions and 129 deletions.
117 changes: 38 additions & 79 deletions frontend/src/pages/Admin/Components/Resource/Resource.jsx
Original file line number Diff line number Diff line change
@@ -1,81 +1,43 @@
import React, { useEffect, useState } from "react";
import { END_POINT } from "../../../../config/api";
import axios from "axios";
import { SimpleToast } from "../../../../components/util/Toast";
import "./resource.module.scss";
import style from "./resource.module.scss";
import { deleteResource, getResources } from "../../../../service/Resources";
import Loader from "../../../../components/util/Loader";

export function Resource() {
const [resourses, setResources] = useState([]);
const [loading, setLoading] = useState(false);
const [openError, setOpenError] = useState(false);
const [openDeleteToast, setDeleteToast] = useState(false);
const [openDeleteError, setDeleteError] = useState(false);

const [toast, setToast] = useState({
toastStatus: false,
toastType: "",
toastMessage: "",
});

useEffect(() => {
const token = localStorage.getItem("token");
const fetchResource = async () => {
try {
const data = await axios.get(`${END_POINT}/resources/getresources`, {
headers: { Authorization: `Bearer ${token}` },
});
const resource = await data.data;
setResources(resource);
setLoading(true);
} catch (err) {
setOpenError(true);
setLoading(true);
}
};
fetchResource();
}, []);

const onClickDelete = async (id) => {
const token = localStorage.getItem("token");
setLoading(false)
try{
const response = await axios.delete(`${END_POINT}/resources/deleteResource`, {
headers: { Authorization: `Bearer ${token}` },
data: { resourceId: id },
});
const message = await response.data;
setLoading(true)
if(message.message === 'resource deleted'){
setDeleteToast(true);
const filteredResources = resourses.filter((resource) => {
return resource._id !== id;
})
setResources(filteredResources);
}
else{
setDeleteError(true);
}
}
catch(err){
setDeleteError(true);
setLoading(true);
}
}

const handleCloseToast = (event, reason) => {
if (reason === "clickaway") {
return;
}
setOpenError(false);
const fetchResource = async () => {
setLoading(false);
const resource = await getResources(setToast, toast);
setResources(resource);
setLoading(true);
};

const handleDeleteToast = (event, reason) => {
if (reason === "clickaway") {
return;
}
setDeleteToast(false);
const onClickDelete = async (id) => {
setLoading(false);
await deleteResource(id, setToast, toast);
await fetchResource();
setLoading(true);
};

const handleDeleteError = (event, reason) => {
if(reason === "clickaway") {
const handleCloseToast = (event, reason) => {
if (reason === "clickaway") {
return;
}
setDeleteError(false);
setToast({ ...toast, toastStatus: false });
};

return (
Expand Down Expand Up @@ -119,33 +81,30 @@ export function Resource() {
URL
</button>
</a>
<button className={style["button-delete"]} onClick={() => onClickDelete(resource._id)}>Delete</button>
<button
className={style["button-delete"]}
onClick={() => onClickDelete(resource._id)}
>
Delete
</button>
</div>
</div>
);
})}
</div>
) : (
<div className={style["dot-loader"]}></div>
<div className={style["dot-loader"]}>
<Loader />
</div>
)}
{toast.toastStatus && (
<SimpleToast
open={toast.toastStatus}
message={toast.toastMessage}
handleCloseToast={handleCloseToast}
severity={toast.toastType}
/>
)}
<SimpleToast
open={openError}
message="Unable to load the data!"
handleCloseToast={handleCloseToast}
severity="error"
/>
<SimpleToast
open={openDeleteToast}
message="Resource deleted successfully!"
handleCloseToast={handleDeleteToast}
severity="success"
/>
<SimpleToast
open={openDeleteError}
message="Something went wrong. Try again!"
handleCloseToast={handleDeleteError}
severity="error"
/>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import { NavLink, useHistory } from "react-router-dom";
import Joi from "joi-browser";
import { Button2 } from "../../../../components/util/Button/index";
import style from "./resource-sharing-form.module.scss";
import { END_POINT } from "../../../../config/api";
import Loader from "../../../../components/util/Loader";
import { SimpleToast } from "../../../../components/util/Toast";
import { postResources } from "../../../../service/Resources";

export function ResourceSharingForm(props) {
const [resourceToast, setResourceToast] = useState("");
const [openSubmitResourceSuccess, setOpenSubmitResourceSuccess] =
useState(false);
const [isLoading, setIsLoading] = useState(false);
const [resourceToastStatus, setResourceToastStatus] = useState("");
const [toast, setToast] = useState({
toastStatus: false,
toastType: "",
toastMessage: "",
});

let dark = props.theme;

Expand Down Expand Up @@ -57,7 +58,7 @@ export function ResourceSharingForm(props) {
return result.error ? result.error.details[0].message : null;
};

const handleSubmit = (e) => {
const handleSubmit = async (e) => {
e.preventDefault();
const errors = validate();
Object.keys(formdata).map((key) => {
Expand All @@ -72,9 +73,11 @@ export function ResourceSharingForm(props) {
if (errors) {
setSubmitted(false);
} else {
setSubmitted(true);
submitResourceFormData(formdata);
setIsLoading(true);
await postResources(formdata, setToast, toast);
setFormData("");
setIsLoading(false);
setSubmitted(true);
console.log("Submitted");
}
};
Expand All @@ -92,42 +95,11 @@ export function ResourceSharingForm(props) {
setFormErrors(errors);
};

const submitResourceFormData = async (formdata) => {
var api = `${END_POINT}/resources/`;
setIsLoading(true);
return await fetch(api, {
method: "POST",
body: JSON.stringify(formdata),
headers: {
"Content-type": "application/json",
},
})
.then((res) => res.json())
.then((data) => {
if (
data.message === "Database Error" ||
data.message === "Sendgrid Error"
) {
setIsLoading(false);
setResourceToast(data.message);
setResourceToastStatus("error");
} else {
setIsLoading(false);
setResourceToastStatus("success");
setResourceToast(data.message);
setOpenSubmitResourceSuccess(true);
}
})
.catch((err) => {
console.info(err);
});
};

console.log(resourceToast);

const handleCloseResourceToast = () => {
setOpenSubmitResourceSuccess(false);
setResourceToast("");
const handleCloseResourceToast = (event, reason) => {
if (reason === "clickaway") {
return;
}
setToast({ ...toast, toastStatus: false });
};

return (
Expand All @@ -145,7 +117,7 @@ export function ResourceSharingForm(props) {
<Loader height="25vh" />
</div>
</React.Fragment>
) : resourceToastStatus === "error" ? (
) : toast.toastType === "error" ? (
<React.Fragment>
<div className={style["goodbye-card"]}>
<h1 className={style["card-heading"]}>OOPS !</h1>
Expand Down Expand Up @@ -522,13 +494,12 @@ export function ResourceSharingForm(props) {
</form>
</div>
)}

{openSubmitResourceSuccess && (
{toast.toastStatus && (
<SimpleToast
open={openSubmitResourceSuccess}
message={resourceToast}
open={toast.toastStatus}
message={toast.toastMessage}
handleCloseToast={handleCloseResourceToast}
severity={resourceToastStatus}
severity={toast.toastType}
/>
)}
</div>
Expand Down
97 changes: 97 additions & 0 deletions frontend/src/service/Resources.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import {
DELETE_FAIL,
DELETE_SUCCESS,
GET_FAIL,
GET_SUCCESS,
POST_FAIL,
POST_SUCCUSS,
} from "../common/constants";
import { END_POINT } from "../config/api";

const getResources = async (setToast, toast) => {
try {
const response = await fetch(`${END_POINT}/resources/getresources`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
});
const data = await response.json();
setToast({
...toast,
toastMessage: GET_SUCCESS,
toastStatus: true,
toastType: "success",
});
return data.ContactUs;
} catch (err) {
console.log(err);
setToast({
...toast,
toastMessage: GET_FAIL,
toastStatus: true,
toastType: "error",
});
}
};

const postResources = async (data, setToast, toast) => {
try {
const response = await fetch(`${END_POINT}/resources/`, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: JSON.stringify(data),
});
const _data = await response.json();
setToast({
...toast,
toastMessage: POST_SUCCUSS,
toastStatus: true,
toastType: "success",
});
return _data;
} catch (err) {
console.log(err);
setToast({
...toast,
toastMessage: POST_FAIL,
toastStatus: true,
toastType: "error",
});
}
};

const deleteResource = async (id, setToast, toast) => {
try {
const response = await fetch(`${END_POINT}/resources/deleteResource`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ resourceId: id }),
});

const data = await response.json();
setToast({
...toast,
toastMessage: DELETE_SUCCESS,
toastStatus: true,
toastType: "success",
});
return data;
} catch (err) {
console.log(err);
setToast({
...toast,
toastMessage: DELETE_FAIL,
toastStatus: true,
toastType: "error",
});
}
};

export { getResources, postResources, deleteResource };

0 comments on commit ae4168f

Please sign in to comment.