Skip to content
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

completed react tasks #17

Open
wants to merge 15 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
82 changes: 63 additions & 19 deletions components/AddTask.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,69 @@
export default function AddTask() {
import axios from "../utils/axios"
import { API_URL } from "../utils/constants"
import { useAuth } from "../context/auth"
import React, { useState } from "react"
import { Button, Container, Col, Row, Form } from "react-bootstrap"
import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

export default function AddTask(props) {
const { token } = useAuth()
const [tasks, setTasks] = useState([])
const [title, setTitle] = useState('')

function handleChange(event) {
const newTitle = event.target.value
setTitle(newTitle)
}

function notify(){
toast.success("Task added successfully!", {
position: "bottom-right",
autoClose: 3000
})
}

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.
*/
axios({
Swayamshu marked this conversation as resolved.
Show resolved Hide resolved
url: API_URL + 'todo/create/',
method: 'post',
data: {
title: title
},
headers: {
Authorization: 'Token ' + token
}
}).then(response => {
console.log(response);
setTasks(prevTasks => {
return [...prevTasks, title]
})
setTitle('')
props.onClick();
notify()
}).catch(error => {
console.log(error);
toast.error("Couldn't add task!", {
position: "bottom-right",
})
})
}

return (
<div className='flex items-center max-w-sm mt-24'>
<input
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'
/>
<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}
>
Add Task
</button>
<div className="pt-20 input-container">
<Container fluid={10}>
<Row>
<Col className="task-input">
<Form>
<Form.Control size="lg" className="add-task-input" onChange={handleChange} value={title} type="text" placeholder="Enter Task" />
</Form>
</Col>
<Col md="auto" className="task-input">
<Button variant="outline-success" size="lg" className="add-task-btn" onClick={addTask} type='button'>Add Task</Button>
</Col>
</Row>
</Container>
<ToastContainer />
</div>
)
}
87 changes: 75 additions & 12 deletions components/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,80 @@
import React, { useEffect, useState } from "react"
import axios from "axios"
import { useRouter } from "next/router"
import { useAuth } from "../context/auth"
import { API_URL } from "../utils/constants"
import { useCookies } from "react-cookie"
import { Button } from "react-bootstrap"
import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

export default function RegisterForm() {
const router = useRouter()
const { setToken } = useAuth()
const [profileName, setProfileName] = useState('')
const [avatarImage, setAvatarImage] = useState('#')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')

function validFieldValues(username, password) {
if (username === '' || password == '')
return false
return true
}

function handleUsernameChange(event) {
const newUsername = event.target.value
setUsername(newUsername)
}

function handlePasswordChange(event) {
const newPassword = event.target.value
setPassword(newPassword)
}

const login = () => {
/***
* @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)
*/
toast.info("Logging in...", {
position: "bottom-right",
})

if (validFieldValues(username, password)) {
console.log("logging in...")

axios({
url: API_URL + 'auth/login/',
method: 'post',
data: {
username: username,
password: password
}
}).then(res => {
setToken(res.data.token)
setAvatarImage(
'https://ui-avatars.com/api/?name=' +
res.data.name +
'&background=fff&size=33&color=007bff'
)
setProfileName(res.data.name)
name = res.data.name
router.push('/')
}).catch(error => {
console.log(error)
toast.error("Login error!", {
position: "bottom-right",
})
})
}
}

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='container max-w-sm flex-col items-center justify-center px-5'>
<div className='bg-white px-6 py-8 rounded shadow-md text-black w-full'>
<h1 className='mb-8 text-3xl text-center'>Login</h1>
<input
type='text'
onChange={handleUsernameChange}
value={username}
className='block border border-grey-light w-full p-3 rounded mb-4'
name='inputUsername'
id='inputUsername'
Expand All @@ -23,21 +83,24 @@ export default function RegisterForm() {

<input
type='password'
onChange={handlePasswordChange}
value={password}
className='block border border-grey-light w-full p-3 rounded mb-4'
name='inputPassword'
id='inputPassword'
placeholder='Password'
/>

<button
<Button variant="outline-success"
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}
>
size="lg"
style={{ width: "100%"}}
onClick={login}>
Login
</button>
</Button>
</div>
</div>
<ToastContainer />
</div>
)
}
132 changes: 81 additions & 51 deletions components/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,91 @@
/* eslint-disable @next/next/no-img-element */
import Link from 'next/link'
import { useAuth } from '../context/auth'
/**
*
* @todo Condtionally render login/register and Profile name in NavBar
*/
import { Navbar, Nav, Button, Dropdown, DropdownButton, Image } from 'react-bootstrap'
import { useCookies } from 'react-cookie'
import { useState, useEffect } from 'react'
import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

export default function Nav() {
const { logout, profileName, avatarImage } = useAuth()
export default function NavBar() {
const { token, logout, profileName, avatarImage } = useAuth()
const [cookies, setCookies, removeCookies] = useCookies(['auth'])
const [notLoggedIn, setNotLoggedIn] = useState(true)
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
const [date, setDate] = useState(new Date().getDate())
const [month, setMonth] = useState(new Date().getMonth())
const hr = (new Date().getHours() + 11) % 12 + 1
const suf = new Date().getHours() > 11 ? "PM" : "AM"
const [suffix, setSuffix] = useState(suf)
const [hour, setHour] = useState(hr)
const min = new Date().getMinutes() > 9 ? new Date().getMinutes() : ('0' + new Date().getMinutes())
const [minute, setMinute] = useState(min)

function updateTime() {
const newHour = (new Date().getHours() + 11) % 12 + 1
const newSuffix = new Date().getHours() > 11 ? "PM" : "AM"
const newMinute = new Date().getMinutes() > 9 ? new Date().getMinutes() : ('0' + new Date().getMinutes())

setDate(new Date().getDate())
setMonth(new Date().getMonth())
setHour(newHour)
setMinute(newMinute)
setSuffix(newSuffix)
}

setInterval(updateTime, 1000)

useEffect(() => {
if (token) {
setNotLoggedIn(false)
} else {
setNotLoggedIn(true)
}
}, [token])

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'
<Navbar collapseOnSelect expand="lg" bg="primary" variant="dark">
<Navbar.Brand href="/" style={{ marginLeft: "5%" }} className="ml-5 font-bold fs-3">Todo</Navbar.Brand>
<Navbar.Brand className="time nav-items fs-5" style={{ marginLeft: "auto"}}>
{date + " " + months[month] + " " + hour + ":" + minute + " " + suffix}
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" style={{ marginLeft: "auto", marginRight: "30px" }}/>

<Navbar.Collapse id="responsive-navbar-nav">
<Nav className={ !notLoggedIn ? "hideme" : null + "ml-5 fs-5"}>
<Nav.Link href="/login" className="nav-items">Login</Nav.Link>
<Nav.Link href="/register" className="nav-items">Register</Nav.Link>
</Nav>

<Nav className="ml-auto mr-5">
<div className="avatar-box">
<div className="avatar">
<Image style={{ marginTop: "20%" }} src={avatarImage} roundedCircle />
</div>

<div className="avatar">
<DropdownButton
key="1"
id="dropdown-button-drop"
size="lg"
title={profileName}
>
<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>
<Dropdown.Item
onClick={() => {
toast.info("Logged out!", {
position: "bottom-right",
autoClose: 2000
})
logout()
}}
>Logout
</Dropdown.Item>
</DropdownButton>
</div>
</div>
</div>
</ul>
</nav>
</Nav>
</Navbar.Collapse>
<ToastContainer />
</Navbar>
)
}
Loading