Skip to content

Web-Week3 task completed #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 54 additions & 3 deletions components/AddTask.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,58 @@
export default function AddTask() {
import { useRef, useState } from "react";
import axios from "../utils/axios";
import { useAuth } from "../context/auth";

export default function AddTask({getTasks}) {
const addTaskButton = useRef(null);
const {token, successToast, errorToast, setIsLoading} = useAuth();
const [title,setTitle] = useState("");
const [buttonActive, setButtonActive] = useState(false);

const keyPressHandler = (event) => {
if (event.key === "Enter") {
addTaskButton.current.click();
setButtonActive(true);
setTimeout(() => {
if (addTaskButton.current !== null) {
setButtonActive(false);
}
}, 2000)
}
}

const addTask = () => {
/**
* @todo Complete this function.
* @todo 1. Send the request to add the task to the backend server.
* @todo 2. Add the task in the dom.
*/
//TODO 1: Sending the request to add the task to the backend server.
if(title.trim().length) {
const dataForApiRequest = {
title: title.trim()
}
setIsLoading(true);
axios
.post('/todo/create/',dataForApiRequest,{
headers: {
Authorization: "Token " + token
}
})
.then(async data => {
setTitle("")
//TODO 2: Getting the tasks and setting in the tasks array
await getTasks();
setIsLoading(false);
successToast("Task added successfully")
})
.catch(err => {
setIsLoading(false);
errorToast(err.message);
});
}
else {
errorToast("Task can't be empty");
}
};

return (
Expand All @@ -13,11 +61,14 @@ export default function AddTask() {
type="text"
className="todo-add-task-input px-4 py-2 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm border border-blueGray-300 outline-none focus:outline-none focus:ring w-full"
placeholder="Enter Task"
value={title}
onChange={(e) => setTitle(e.target.value)}
onKeyDown={keyPressHandler}
/>
<button
type="button"
className="todo-add-task bg-transparent hover:bg-green-500 text-green-700 text-sm hover:text-white px-3 py-2 border border-green-500 hover:border-transparent rounded"
onClick={addTask}>
className={`transition-all duration-700 todo-add-task hover:bg-green-500 text-sm hover:text-white px-3 py-2 hover:border-transparent rounded ${buttonActive? "bg-green-500 text-white":"bg-transparent text-green-700 border border-green-500 "}`}
onClick={addTask} ref={addTaskButton}>
Add Task
</button>
</div>
Expand Down
88 changes: 83 additions & 5 deletions components/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,93 @@
export default function RegisterForm() {
const login = () => {
import { useRef, useState } from "react";
import { useAuth } from "../context/auth";
import { useRouter } from "next/router";
import axios from "../utils/axios";
import Link from "next/link";

export default function LoginForm() {
const loginButton = useRef(null);
const { setToken , successToast, errorToast, setIsLoading} = useAuth();
const router = useRouter();

const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [buttonActive, setButtonActive] = useState(false);


const keyPressHandler = (event) => {
if (event.key === "Enter") {
loginButton.current.click();
setButtonActive(true);
setTimeout(() => {
if (loginButton.current !== null) {
setButtonActive(false);
}
}, 2000)
}
}

//TODO 1: Function for form validation
const loginFieldsAreValid = (username, password) => {
if (username === "" || password === "") {
errorToast("Fields cannot be empty")
return false;
}
return true;
}

const login = (e) => {
/***
* @todo Complete this function.
* @todo 1. Write code for form validation.
* @todo 2. Fetch the auth token from backend and login the user.
* @todo 3. Set the token in the context (See context/auth.js)
*/
e.preventDefault();
if (loginFieldsAreValid(username, password)) {
const dataForApiRequest = {
username,
password,
};

//TODO 2: Fetching the auth token
setIsLoading(true);
axios
.post("auth/login/", dataForApiRequest)
.then(function ({ data }) {
//TODO 3: Setting the auth token in the context
setToken(data.token);
setUsername("");
setPassword("");
setIsLoading(false);
successToast("Logged In Successfully");
router.push("/");
})
.catch(error => {
setIsLoading(false);
if(error.response) {
errorToast(error.response.data.non_field_errors[0])
}
else {
console.log(error.message)
}
});
}
};

return (
<div className="bg-grey-lighter min-h-screen flex flex-col">
<div className="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2">
<div className="bg-white px-6 py-8 rounded shadow-md text-black w-full">
<div className="bg-white px-6 py-8 rounded-xl shadow-2xl text-black w-full">
<h1 className="mb-8 text-3xl text-center">Login</h1>
<input
type="text"
className="block border border-grey-light w-full p-3 rounded mb-4"
name="inputUsername"
id="inputUsername"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={keyPressHandler}
/>

<input
Expand All @@ -27,14 +96,23 @@ export default function RegisterForm() {
name="inputPassword"
id="inputPassword"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={keyPressHandler}
/>

<button
type="submit"
className="w-full text-center py-3 rounded bg-transparent text-green-500 hover:text-white hover:bg-green-500 border border-green-500 hover:border-transparent focus:outline-none my-1"
onClick={login}>
className={`w-full text-center py-3 rounded border hover:text-white hover:bg-green-500 hover:border-transparent focus:outline-none my-1 transition-all duration-500 ${buttonActive?"text-white bg-green-500 border-transparent":"bg-transparent text-green-500 border-green-500"}`}
onClick={login} ref={loginButton}>
Login
</button>

<hr className="relative top-3" />

<div className="flex justify-center relative top-5 text-sm text-gray-500">
Don&apos;t have an account?<span className="text-blue-600"><Link href="/register"> &nbsp; Register</Link></span>
</div>
</div>
</div>
</div>
Expand Down
98 changes: 55 additions & 43 deletions components/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,58 +2,70 @@
/* eslint-disable @next/next/no-img-element */
import Link from "next/link";
import { useAuth } from "../context/auth";
import { ToastContainer } from "react-toastify";
import Spinner from "./Spinner";
/**
*
* @todo Condtionally render login/register and Profile name in NavBar
*/

export default function Nav() {
const { logout, profileName, avatarImage } = useAuth();
const { profileName, avatarImage, logout, token, isLoading } = useAuth();

return (
<nav className="bg-blue-600">
<ul className="flex items-center justify-between p-5">
<ul className="flex items-center justify-between space-x-4">
<li>
<Link href="/" passHref={true}>
<a>
<h1 className="text-white font-bold text-xl">Todo</h1>
</a>
</Link>
</li>
</ul>
<ul className="flex">
<li className="text-white mr-2">
<Link href="/login">Login</Link>
</li>
<li className="text-white">
<Link href="/register">Register</Link>
</li>
</ul>
<div className="inline-block relative w-28">
<div className="group inline-block relative">
<button className="bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded inline-flex items-center">
<img src={avatarImage} />
<span className="mr-1">{profileName}</span>
<svg
className="fill-current h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20">
<path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
</svg>
</button>
<ul className="absolute hidden text-gray-700 pt-1 group-hover:block">
<li className="">
<a
className="rounded-b bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap"
href="#"
onClick={logout}>
Logout
</a>
</li>
</ul>
</div>
</div>
<ToastContainer />
<ul className="flex items-center justify-between py-3 px-12">
<li className="ml-3">
<Link href="/" passHref={true}>
<a>
<h1 className="text-white font-bold text-xl">Todo</h1>
</a>
</Link>
</li>
{/* //*Spinner loads if isLoading is true (from Context) */}
{
isLoading ? <Spinner/> : <div className="h-5"></div>
}
{/* //TODO: If token does no exist, render login/register; otherwise Profile name */}
{
!token ?
<li>
<ul className="flex">
<li className="border border-white text-white px-6 py-2 rounded-2xl hover:text-blue-600 hover:bg-white transition-all duration-500 mx-4">
<Link href="/login">Login</Link>
</li>
<li className="border border-white text-white px-6 py-2 rounded-2xl hover:text-blue-600 hover:bg-white transition-all duration-500 mx-4">
<Link href="/register">Register</Link>
</li>
</ul>
</li> :
<li className="inline-block relative h-12">
<div className="group inline-block relative ">
<button className="bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded-xl inline-flex items-center hover:bg-gray-400 transition-all duration-500">
<img src={avatarImage} className="mx-3" />
<span className="mr-1">{profileName}</span>
<svg
className="fill-current h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20">
<path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
</svg>
</button>
<ul className="absolute hidden text-gray-700 pt-1 group-hover:block w-full text-center">
<li className="">
<span
className="transition-all duration-500 rounded-b bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap cursor-pointer"
onClick={logout}>
Logout
</span>
</li>
</ul>
</div>
</li>
}


</ul>
</nav>
);
Expand Down
Loading