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

done, some polish left #29

Open
wants to merge 4 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
6 changes: 5 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"extends": ["next/babel", "next/core-web-vitals"]
"extends": ["next", "next/core-web-vitals"],
"rules": {
// Other rules
"@next/next/no-img-element": "off"
}
}
36 changes: 34 additions & 2 deletions components/AddTask.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
export default function AddTask() {
import axios from "../utils/axios"
import { useState } from "react"
import { useAuth } from "../context/auth"
import toast, { Toaster } from 'react-hot-toast'

export default function AddTask({ getTasks }) {
const [newTask, setNewTask] = useState('')
const { token } = useAuth()

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.
*/

if (token){
if (newTask == '') {
toast.error('Enter some data')
return
}
const dataForApiPost = {
title : newTask,
}
axios.post('todo/create/', dataForApiPost,{
headers:{
Authorization: 'Token '+ token
}
}).then((res)=>{
setNewTask('')
// setCheck(!check)
toast.success('Task added successfully!')
getTasks("getTasks ran from addTask :)")
}).catch((err)=>{
toast.error('Failed to add task')
})
}
}
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'
className='font-body 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'
onChange={(e) => setNewTask(e.target.value)}
/>
<button
type='button'
Expand All @@ -20,6 +51,7 @@ export default function AddTask() {
>
Add Task
</button>
<Toaster />
</div>
)
}
59 changes: 57 additions & 2 deletions components/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,65 @@
import { useState } from 'react'
import axios from '../utils/axios'
import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'
import toast, { Toaster } from 'react-hot-toast'
import { API_URL } from '../utils/constants';

export default function RegisterForm() {
const login = () => {
const { setToken } = useAuth()
const router = useRouter()

const [password, setPassword] = useState('')
const [username, setUsername] = useState('')

function loginFieldsAreValid(
username,
password
) {
if (username === '' || password === '') {
console.log(username, password)
console.log('Please fill all the fields correctly.')
return false
}
return true
}

function 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)) {
console.log('Please wait...')

const dataForApiRequest = {
username: username,
password: password,
}

axios({
url: API_URL + "auth/login/",
method: "POST",
data: dataForApiRequest,
})
.then((res) => {
toast("User logged in successfully");
const token = res.data.token;
setToken(token);
localStorage.setItem("token", token)
router.push("LOGIN", "/");
})
.catch(function (err) {
toast("Invalid credentials! Please try again.");

});
}
}

return (
<div className='bg-grey-lighter min-h-screen flex flex-col'>
Expand All @@ -19,6 +72,7 @@ export default function RegisterForm() {
name='inputUsername'
id='inputUsername'
placeholder='Username'
onChange={(e) => setUsername(e.target.value)}
/>

<input
Expand All @@ -27,6 +81,7 @@ export default function RegisterForm() {
name='inputPassword'
id='inputPassword'
placeholder='Password'
onChange={(e) => setPassword(e.target.value)}
/>

<button
Expand Down
9 changes: 7 additions & 2 deletions components/Nav.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable @next/next/no-img-element */
import Link from 'next/link'
import router from 'next/router';
import { useAuth } from '../context/auth'
/**
*
* @todo Condtionally render login/register and Profile name in NavBar
*/

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

return (
<nav className='bg-blue-600'>
Expand Down Expand Up @@ -48,7 +49,11 @@ export default function Nav() {
<a
className='rounded-b bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap'
href='#'
onClick={logout}
onClick={() => {
logout()
window.location.href = "/login"
}
}
>
Logout
</a>
Expand Down
82 changes: 71 additions & 11 deletions components/TodoListItem.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
/* eslint-disable @next/next/no-img-element */
import { useState } from "react"
import { useAuth } from "../context/auth"
import axios from "../utils/axios"
import { API_URL } from "../utils/constants"
import toast, { Toaster } from 'react-hot-toast';
import { useEffect } from "react";

export default function TodoListItem({ title, id, getTasks }) {
const { token } = useAuth()
const [editStatus, setEditStatus] = useState(false)
const [updateData,setupdateData] = useState('')
const [input, setInput] = useState(title)

useEffect(() => {
console.log("input changed!")
}, [input])

export default function TodoListItem() {
const editTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Update the dom accordingly
*/

setEditStatus(!editStatus)
}

const deleteTask = (id) => {
Expand All @@ -14,6 +31,20 @@ export default function TodoListItem() {
* @todo 1. Send the request to delete the task to the backend server.
* @todo 2. Remove the task from the dom.
*/
if (token) {
axios({
method: "delete",
url: API_URL + `todo/${id}/`,
headers:{
Authorization: 'Token ' + token
}
}).then((res)=>{
toast.success('Task deleted succesfully')
getTasks("getTask ran from deleteTask :)")
}).catch((err)=>{
toast.error('Failed to delete')
})
}
}

const updateTask = (id) => {
Expand All @@ -22,34 +53,63 @@ export default function TodoListItem() {
* @todo 1. Send the request to update the task to the backend server.
* @todo 2. Update the task in the dom.
*/

if (updateData == '') {
toast.error('Please enter task title')
return
}
const dataForUpdate = {
title: updateData
}
if(token){
axios.patch('todo/'+id+'/',dataForUpdate,{
headers:{
Authorization: 'Token ' + token
}
}).then((res)=>{
setEditStatus(!editStatus)
setupdateData('')
toast.success('Update successfull!')
getTasks("getTask ran from updateTask :)")
}).catch((err)=>{
toast.error('Update failed!')
})
}
}

return (
<>
<li className='border flex border-gray-500 rounded px-2 py-2 justify-between items-center mb-2'>
<input
id='input-button-1'
id={'input-button-'+id}
type='text'
className='hideme appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring todo-edit-task-input'
className={`${(!editStatus) ? 'hideme' : ""} font-body appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring todo-edit-task-input`}
placeholder='Edit The Task'
value={input}
onInput={(e) => {
setInput(e.target.value)
}}
onChange={(e)=>setupdateData(e.target.value)}
/>
<div id='done-button-1' className='hideme'>
<div id={'done-button-'+id} className={`${(!editStatus) ? 'hideme' : ""}`}>
<button
className='bg-transparent hover:bg-gray-500 text-gray-700 text-sm hover:text-white py-2 px-3 border border-gray-500 hover:border-transparent rounded todo-update-task'
type='button'
onClick={updateTask(1)}
onClick={() => updateTask(id)}
>
Done
</button>
</div>
<div id='task-1' className='todo-task text-gray-600'>
Sample Task 1
<div id={'task-'+id} className='todo-task text-gray-600'>
{`${(!editStatus) ? title : ""}`}
</div>
<span id='task-actions-1' className=''>
<span id={'task-actions-'+id} className=''>
<button
style={{ marginRight: '5px' }}
type='button'
onClick={editTask(1)}
onClick={() => {
editTask(id)
}}
className='bg-transparent hover:bg-yellow-500 hover:text-white border border-yellow-500 hover:border-transparent rounded px-2 py-2'
>
<img
Expand All @@ -61,8 +121,8 @@ export default function TodoListItem() {
</button>
<button
type='button'
className='bg-transparent hover:bg-red-500 hover:text-white border border-red-500 hover:border-transparent rounded px-2 py-2'
onClick={deleteTask(1)}
className='bg-transparent hover:bg-yellow-500 hover:text-white border border-yellow-500 hover:border-transparent rounded px-2 py-2'
onClick={() => deleteTask(id)}
>
<img
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486661/CSOC/delete.svg'
Expand Down
17 changes: 17 additions & 0 deletions middlewares/auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
/***
* @todo Redirect the user to login page if token is not present.
*/
import { useRouter } from "next/router";
import { useEffect } from "react";
import { useAuth } from "../context/auth";

function authRequired() {
const router = useRouter()
const { token } = useAuth()

useEffect(() => {
if (!token) {
router.push("/login")
}
console.log("useEffect ran")
}, [])
}

export default authRequired
18 changes: 17 additions & 1 deletion middlewares/no_auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/***
* @todo Redirect the user to main page if token is present.
*/
*/
import { useRouter } from "next/router";
import { useEffect } from "react";
import { useAuth } from "../context/auth";

function noAuthRequired() {
const router = useRouter()
const { token } = useAuth()

useEffect(() => {
if (token) {
router.push("/")
}
}, [])
}

export default noAuthRequired
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"react": "17.0.2",
"react-cookie": "^4.0.3",
"react-dom": "17.0.2",
"react-hot-toast": "^2.2.0",
"tailwindcss": "^2.2.2"
},
"devDependencies": {
Expand Down
Loading