Skip to content

Instantly share code, notes, and snippets.

@rahulmore01
Created September 5, 2023 14:27
Show Gist options
  • Save rahulmore01/8ab24446c4e6b98029045b945a4b7bdf to your computer and use it in GitHub Desktop.
Save rahulmore01/8ab24446c4e6b98029045b945a4b7bdf to your computer and use it in GitHub Desktop.
blog - navbar
"use client";
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setUserData, setLoading, setError } from "@/redux/features/userSlice";
import axios from "axios";
import Link from "next/link";
import { TbPencilMinus } from "react-icons/tb";
import SearchBar from "../searchBar/page";
import Image from "next/image";
import UserInitial from "./userInitial/page";
interface MyJwtPayload {
id: string;
username: string;
email: string;
}
interface UserState {
userData: MyJwtPayload | null;
loading: boolean;
error: string | null;
}
console.log("setUserData", setUserData);
const Navbar = () => {
const dispatch = useDispatch();
const userState = useSelector((state: { user: UserState }) => state.user);
const [showNavbar, setShowNavbar] = useState(true);
const [prevScrollY, setPrevScrollY] = useState(0);
const isLogin = true;
useEffect(() => {
async function fetchUserData() {
try {
dispatch(setLoading(true));
const response = await axios.get("/api/users/currentuserdata");
dispatch(setUserData(response.data.data));
dispatch(setLoading(false));
} catch (error: any) {
dispatch(setError(error.message));
dispatch(setLoading(false));
}
}
fetchUserData();
}, [dispatch]);
useEffect(() => {
const handleScroll = () => {
const currentScrollY = window.scrollY;
setShowNavbar(currentScrollY <= prevScrollY || currentScrollY < 20);
setPrevScrollY(currentScrollY);
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, [prevScrollY]);
return (
<div
className={`bg-white border-b-[1px] fixed top-0 w-full transition-transform ${
showNavbar ? "translate-y-0" : "-translate-y-full"
} duration-300 ease-in-out`}
>
<div className="flex h-20 pl-20 pr-20 justify-between items-center monu_ex_reg">
<div className="">
<Image
alt="no img"
src="/images/devpaper.png"
width={140}
height={100}
></Image>
</div>
<div className="flex items-center justify-center gap-8">
<SearchBar />
<Link href="/blogs/createblog">
<button className="flex gap-2 bg-bgBlue px-5 py-2 rounded-full text-white">
<TbPencilMinus className="w-5 h-5" /> Write
</button>
</Link>
{isLogin === true ? (
<div className="bg-transparent p-[2px] rounded-full border-2 border-bgBlue">
<UserInitial />
</div>
) : (
<Link href="/login">
<button> Login</button>
</Link>
)}
</div>
</div>
</div>
);
};
export default Navbar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment