Skip to content

Commit

Permalink
chore: tidy up, styled loading
Browse files Browse the repository at this point in the history
  • Loading branch information
felixtanhm committed May 10, 2024
1 parent ad96ec9 commit 57a14d1
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
MoonIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { NavLink } from "react-router-dom";
import { NavLink, useNavigate } from "react-router-dom";
import { DarkModeContext } from "../App";

const navigation = [
Expand All @@ -19,6 +19,7 @@ function classNames(...classes) {
}

export default function NavBar({ route }) {
const navigate = useNavigate();
const { darkMode, setDarkMode } = useContext(DarkModeContext);

return (
Expand Down Expand Up @@ -56,6 +57,10 @@ export default function NavBar({ route }) {
<NavLink
key={item.name}
to={item.href}
onClick={(e) => {
e.preventDefault();
navigate(`${item.href}`);
}}
className={({ isActive }) => {
return isActive
? "rounded-md bg-gray-200 px-3 py-2 text-sm font-medium text-gray-900 dark:bg-gray-900 dark:text-white"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,29 @@ import { HeartIcon as HeartIconSolid } from "@heroicons/react/24/solid";
import PokeType from "./PokeType";
import { useNavigate } from "react-router-dom";

function PokeCard({ pokemon, isFav, toggleFavorite }) {
function PokeCard({ pokemon, isFav }) {
const navigate = useNavigate();

return (
<div
className="flex cursor-pointer flex-col items-center rounded-md bg-gray-200 p-4 dark:bg-gray-500/20"
className="flex h-fit cursor-pointer flex-col items-center rounded-md bg-gray-200 p-4 dark:bg-gray-500/20"
onClick={() => {
navigate(`/pokemon/${pokemon.dexId}`);
}}
>
<div className="absolute self-end">
<button
type="button"
className="relative rounded-full p-1 text-gray-500 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:text-gray-400 dark:hover:text-white dark:focus:ring-white dark:focus:ring-offset-gray-800"
onClick={(e) => {
toggleFavorite(e, pokemon.dexId);
}}
>
<span className="sr-only">Favorite Pokemon</span>
{isFav && (
<HeartIconSolid
className="h-6 w-6 text-rose-500 dark:text-rose-800 "
aria-hidden="true"
/>
)}
{!isFav && (
<HeartIconOutline className="h-6 w-6" aria-hidden="true" />
)}
</button>
{isFav && (
<HeartIconSolid
className="relative h-6 w-6 text-rose-500 dark:text-rose-800 "
aria-hidden="true"
/>
)}
{!isFav && (
<HeartIconOutline
className="relative h-6 w-6 text-gray-500"
aria-hidden="true"
/>
)}
</div>
<img className="mt-6 max-w-24" src={pokemon.avatar}></img>
<div className="flex flex-col items-center gap-2 p-2">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ function PokeDetails() {
const [state, setState] = useState("loading");
let isFav = null;

function handleFavorite(favoriteList) {
const { prevFavs, nextFavs } = toggleFavorite(favoriteList);
function handleFavorite() {
const { prevFavs, nextFavs } = toggleFavorite(user.favorites);
const data = {
objectId: user._id,
favorites: nextFavs,
Expand Down Expand Up @@ -106,7 +106,7 @@ function PokeDetails() {
type="button"
className="flex w-36 items-center justify-center gap-1 rounded-md bg-gray-200 px-3 py-2 text-sm font-medium text-gray-900 hover:bg-gray-100 dark:bg-gray-500/20 dark:text-gray-300 dark:hover:bg-gray-700"
onClick={() => {
handleFavorite(user.favorites);
handleFavorite();
}}
>
<span className="sr-only">Favorite Pokemon</span>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,25 @@ import { useState, useContext } from "react";
import { UserContext } from "../App";
import PokeCard from "./PokeCard";

function PokeList() {
function PokeList({ path }) {
const [list, setList] = useState(null);
const [state, setState] = useState("loading");
const [error, setError] = useState(null);
const [page, setPage] = useState(path);
const { user, setUser } = useContext(UserContext);

async function fetchList(currData) {
try {
const nextId = currData.length
? currData[currData.length - 1]?.dexId
: currData.length;

const response = await fetch(
`http://localhost:3000/pokemon?cursor=${nextId}`,
);
let url;
if (path === "home") {
const nextId = currData.length
? currData[currData.length - 1]?.dexId
: currData.length;
url = `http://localhost:3000/pokemon?cursor=${nextId}`;
}
if (path === "favorites") {
url = `http://localhost:3000/users/favorites`;
}
const response = await fetch(url);

if (!response.ok) {
let errorMessage = `Failed to fetch data. Status: ${response.status}`;
Expand All @@ -34,42 +38,42 @@ function PokeList() {

setList(nextList);
setState("success");
// }
setPage(path);
} catch (error) {
console.log(error);
setState("error");
// setError(error);
}
}

function toggleFavorite(e, dexId) {
e.stopPropagation();
console.log(dexId);
}

if (!list) {
if (!list || path !== page) {
fetchList([]);
}

console.log(user);
return (
<div className="flex flex-col items-center gap-8 p-4 pb-12 sm:p-6 lg:p-8 dark:bg-gray-800">
{state === "error" && <p className="h-screen">Error</p>}
{state === "loading" && !list && <p className="h-screen">Loading...</p>}
{state === "loading" && !list && (
<p className="h-screen text-3xl font-bold text-gray-500">Loading...</p>
)}
{list && (
<>
<div className="grid w-full max-w-7xl grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6">
<div className="grid min-h-screen w-full max-w-7xl grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6">
{list.data.map((item) => {
return (
<PokeCard
pokemon={item}
isFav={true}
toggleFavorite={toggleFavorite}
isFav={
path === "favorites"
? true
: user.favorites.includes(item._id)
}
key={item._id}
></PokeCard>
);
})}
</div>
{list.data.length < 151 && (
{list.data.length < 151 && path !== "favorites" && (
<button
className="w-fit min-w-32 rounded-md bg-gray-200 px-3 py-2 text-sm font-medium text-gray-900 hover:bg-gray-300 dark:hover:bg-gray-100"
disabled={state === "loading"}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,17 @@ import {
createRoutesFromElements,
} from "react-router-dom";
import App from "./App.jsx";
import Home from "./components/Home";
import Test from "./components/Test.jsx";
import PokeList from "./components/PokeList";
import PokeDetails from "./components/PokeDetails.jsx";
import "./reset.css";
import "./index.css";

const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<App />}>
<Route index element={<Home text="home" />}></Route>
<Route index element={<PokeList path="home" />}></Route>
<Route path="pokemon/:dexId" element={<PokeDetails />}></Route>
<Route path="favorites" element={<Test text="favs" />}></Route>
<Route path="favorites" element={<PokeList path="favorites" />}></Route>
</Route>,
),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const Pokemons = require("../models/pokemons");
const PokeDetails = require("../models/pokeDetails");
const Users = require("../models/users");

exports.pokeList = async function (req, res, next) {
try {
Expand All @@ -18,6 +19,24 @@ exports.pokeList = async function (req, res, next) {
}
};

exports.pokeFavs = async function (req, res, next) {
try {
const { favorites } = await Users.findOne({ _id: req.query.user }).exec();
if (!favorites) res.status(200).json({});
const allPokemon = await Pokemons.find({ dexId: { $in: user?.favorites } })
.sort({ dexId: 1 })
.limit(24)
.exec();

res.status(200).json({
data: allPokemon,
});
} catch (error) {
console.log(error);
return next(error);
}
};

exports.pokeDetails = async function (req, res, next) {
try {
const pokemon = await Pokemons.findOne({ dexId: req.params.dexId })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@ exports.getUser = async function (req, res, next) {
}
};

exports.getFavorites = async function (req, res, next) {
try {
const currUser = await Users.findOne({
email: "[email protected]",
})
.populate("favorites")
.exec();

const data = {
totalCount: currUser.favorites.length,
data: currUser.favorites,
};
res.status(200).json(data);
} catch (error) {
next(error);
}
};

exports.updateUser = async function (req, res, next) {
try {
const { objectId, favorites } = req.body;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const userController = require("../controllers/userController");
/* GET users listing. */
router.get("/", userController.getUser);

router.get("/favorites", userController.getFavorites);

router.post("/", userController.updateUser);

module.exports = router;

0 comments on commit 57a14d1

Please sign in to comment.