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 The Tasks #4

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 24 additions & 1 deletion components/AddTask.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
export default function AddTask() {
import axios from 'axios'
export default function AddTask({todos,settodos}) {
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.
*/
const API_BASE_URL = 'https://todo-app-csoc.herokuapp.com/'
const str = (document.querySelector('.todo-add-task-input').value);
if (str === '') return;
{ try { iziToast.show({ title: "Wait", message: 'Adding Todo' }) } catch { } }
axios({
headers: {
Authorization: 'Token ' + document.cookie.substring(6),
},
method: 'post',
url: API_BASE_URL + 'todo/create/',
data: {
title: str
}
}).then(function ({ data, status }) {
{ try { iziToast.success({ title: "Success", message: 'Added Todo' }) } catch { } }
document.querySelector('.todo-add-task-input').value = ''
axios({
headers: { Authorization: 'Token ' + document.cookie.substring(6), },
url: API_BASE_URL + 'todo/',
method: 'get',
}).then((res) => settodos(res.data))
}).catch((err) => { try { iziToast.error({ title: "Error", message: 'Cannot Add Todo' }) } catch { } })
}
return (
<div className='flex items-center max-w-sm mt-24'>
Expand Down
55 changes: 55 additions & 0 deletions components/ListItem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import Image from 'next/image'

const ListItem = ({title,iid,editTask,deleteTask,updateTask}) => {
return (
<li className='border flex border-gray-500 rounded px-2 py-2 justify-between items-center mb-2'>
<input
id={`input-button-${iid}`}
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'
placeholder='Edit The Task'
/>
<div id={`done-button-${iid}`} className='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(iid)}
>
Done
</button>
</div>
<div id={`task-${iid}`} className='todo-task text-gray-600'>
{title}
</div>
<span id={`task-actions-${iid}`} className=''>
<button
style={{ marginRight: '5px' }}
type='button'
onClick={()=>editTask(iid)}
className='bg-transparent hover:bg-yellow-500 hover:text-white border border-yellow-500 hover:border-transparent rounded px-2 py-2'
>
<Image
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486663/CSOC/edit.png'
width='18px'
height='20px'
alt='Edit'
/>
</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(iid)}
>
<Image
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486661/CSOC/delete.svg'
width='18px'
height='22px'
alt='Delete'
/>
</button>
</span>
</li>
)
}

export default ListItem;
33 changes: 33 additions & 0 deletions components/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,48 @@
import axios from 'axios'
import Script from 'next/script'
import { useAuth } from '../context/auth'
import { useEffect} from 'react'
import '../node_modules/izitoast/dist/css/iziToast.min.css'
import checkLogin from '../middlewares/no_auth_required'

export default function RegisterForm() {
const { setToken } = useAuth()
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)
*/
if (document.getElementById('inputUsername').value === '' || document.getElementById('inputPassword').value === '') {
try { iziToast.destroy(); iziToast.error({ title: "Error", message: 'All Fields Are Mandatory' }) } catch {} return;
}
const API_BASE_URL = 'https://todo-app-csoc.herokuapp.com/'
const dataForApiRequest = {
username: document.getElementById('inputUsername').value,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should have make use of React Hooks like useState to manage the states

password: document.getElementById('inputPassword').value
}
try { iziToast.show({ title: "Wait", message: 'Checking Your Credentials' }) } catch { }
axios({
url: API_BASE_URL + 'auth/login/',
method: 'post',
data: dataForApiRequest,
}).then(function ({ data, status }) {
// localStorage.setItem('token', data.token);
setToken(data.token)
window.location.href = '/';
}).catch(function (err) {
{ try { iziToast.destroy(); iziToast.error({ title: "Error", message: 'Invalid Credentials' }) } catch { } }
})
}

useEffect(() => {
checkLogin()
}, [])

return (
<div className='bg-grey-lighter min-h-screen flex flex-col'>
<Script src='https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js'></Script>
<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'>
<h1 className='mb-8 text-3xl text-center'>Login</h1>
Expand Down
11 changes: 6 additions & 5 deletions components/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
/* eslint-disable @next/next/no-img-element */
import Link from 'next/link'
import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'
/**
*
* @todo Condtionally render login/register and Profile name in NavBar
*/

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

const router =useRouter()
return (
<nav className='bg-blue-600'>
<ul className='flex items-center justify-between p-5'>
Expand All @@ -22,15 +23,15 @@ export default function Nav() {
</Link>
</li>
</ul>
<ul className='flex'>
{router.pathname!=='/' && (<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'>
</ul>)}
{router.pathname==='/' && (<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} />
Expand All @@ -55,7 +56,7 @@ export default function Nav() {
</li>
</ul>
</div>
</div>
</div>)}
</ul>
</nav>
)
Expand Down
21 changes: 14 additions & 7 deletions components/RegisterForm.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import React, { useState } from 'react'
import axios from '../utils/axios'
import { useEffect} from 'react'
import { useAuth } from '../context/auth'
import { useRouter } from 'next/router'
import checkLogin from '../middlewares/no_auth_required'
import Script from 'next/script'
import '../node_modules/izitoast/dist/css/iziToast.min.css'

export default function Register() {
const { setToken } = useAuth()
Expand All @@ -27,23 +31,27 @@ export default function Register() {
username === '' ||
password === ''
) {
console.log('Please fill all the fields correctly.')
try{iziToast.destroy();iziToast.error({ title: "Error", message: 'All Fields Are Mandatory' }) }catch {}
return false
}
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
console.log('Please enter a valid email address.')
try{iziToast.destroy();iziToast.error({ title: "Error", message: 'Enter a valid Email Address' }) }catch {}
return false
}
return true
}

useEffect(() => {
checkLogin()
}, [])

const register = (e) => {
e.preventDefault()

if (
registerFieldsAreValid(firstName, lastName, email, username, password)
) {
console.log('Please wait...')
try { iziToast.show({ title: "Wait", message: 'Checking Your Credentials' }) } catch {}

const dataForApiRequest = {
name: firstName + ' ' + lastName,
Expand All @@ -58,18 +66,17 @@ export default function Register() {
)
.then(function ({ data, status }) {
setToken(data.token)
router.push('/')
window.location.href = '/';
})
.catch(function (err) {
console.log(
'An account using same email or username is already created'
)
try{iziToast.destroy();iziToast.error({ title: "Error", message: 'An account using same email or username is already created' }) }catch {}
})
}
}

return (
<div className='bg-grey-lighter min-h-screen flex flex-col'>
<Script src='https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js'></Script>
<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'>
<h1 className='mb-8 text-3xl text-center'>Register</h1>
Expand Down
86 changes: 38 additions & 48 deletions components/TodoListItem.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
/* eslint-disable @next/next/no-img-element */
import ListItem from './ListItem'
import axios from 'axios'

export default function TodoListItem() {
export default function TodoListItem({ todos, settodos }) {
const API_BASE_URL = 'https://todo-app-csoc.herokuapp.com/'
const editTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Update the dom accordingly
*/
document.getElementById('task-' + id).classList.add('hideme');
document.getElementById('task-actions-' + id).classList.add('hideme');
document.getElementById('input-button-' + id).classList.remove('hideme');
document.getElementById('done-button-' + id).classList.remove('hideme');
}

const deleteTask = (id) => {
Expand All @@ -14,6 +21,14 @@ 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.
*/
try { iziToast.show({ title: "Wait", message: 'Deleting Todo..' }) } catch { }
axios({
headers: {
Authorization: 'Token ' + document.cookie.substring(6)
},
url: API_BASE_URL + 'todo/' + id + '/',
method: 'delete',
}).then(function () { settodos(todos.filter(todo => todo.id != id)); try { iziToast.success({ title: "Success", message: 'Todo Deleted' }) } catch { } }).catch((err) => { try { iziToast.error({ title: "Error", message: 'Cannot Delete Todo' }) } catch { } })
}

const updateTask = (id) => {
Expand All @@ -22,57 +37,32 @@ 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.
*/
document.getElementById('task-' + id).classList.remove('hideme');
document.getElementById('task-actions-' + id).classList.remove('hideme');
document.getElementById('input-button-' + id).classList.add('hideme');
document.getElementById('done-button-' + id).classList.add('hideme');
if (document.getElementById('input-button-' + id).value != '') {
try { iziToast.show({ title: "Wait", message: 'Updating Todo..' }) } catch { }
document.getElementById('task-' + id).innerHTML = document.getElementById('input-button-' + id).value;
const data1 = { "id": id, title: document.getElementById('input-button-' + id).value }
axios({
headers: { Authorization: 'Token ' + document.cookie.substring(6) },
url: API_BASE_URL + 'todo/' + id + '/',
method: 'patch',
data: {
title: document.getElementById('input-button-' + id).value
}
}).then(() => { settodos(todos.map((todo) => (todo.id === id) ? data1 : todo)); try { iziToast.destroy(); iziToast.success({ title: "Success", message: 'Todo Updated' }) } catch { } }).catch((err) => { try { iziToast.error({ title: "Error", message: 'Cannot Update Todo' }) } catch { } })
}
}

return (
<>
<li className='border flex border-gray-500 rounded px-2 py-2 justify-between items-center mb-2'>
<input
id='input-button-1'
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'
placeholder='Edit The Task'
/>
<div id='done-button-1' className='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)}
>
Done
</button>
</div>
<div id='task-1' className='todo-task text-gray-600'>
Sample Task 1
</div>
<span id='task-actions-1' className=''>
<button
style={{ marginRight: '5px' }}
type='button'
onClick={editTask(1)}
className='bg-transparent hover:bg-yellow-500 hover:text-white border border-yellow-500 hover:border-transparent rounded px-2 py-2'
>
<img
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486663/CSOC/edit.png'
width='18px'
height='20px'
alt='Edit'
/>
</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)}
>
<img
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486661/CSOC/delete.svg'
width='18px'
height='22px'
alt='Delete'
/>
</button>
</span>
</li>
{
todos.map((user) => (
<ListItem updateTask={() => updateTask(user.id)} deleteTask={() => deleteTask(user.id)} editTask={() => editTask(user.id)} iid={user.id} title={user.title} key={user.id} />
))
}
</>
)
}
4 changes: 2 additions & 2 deletions context/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ export const AuthProvider = ({ children }) => {
}

useEffect(() => {
if (token) {
if (document.cookie!='') {
axios
.get('auth/profile/', {
headers: {
Authorization: 'Token ' + token,
Authorization: 'Token ' + document.cookie.substring(6),
},
})
.then((response) => {
Expand Down
7 changes: 7 additions & 0 deletions middlewares/auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import { useAuth } from '../context/auth'
/***
* @todo Redirect the user to login page if token is not present.
*/
const checkLogin = () => {
// console.log(document.cookie);
if(document.cookie=='')window.location.href = './login'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make use of Framework specific methods rather than using Vanilla JS one

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I have to use router instead of window.location.href and rather than checking document.cookie again and again I should use State ??
Is that all or I am still missing something?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I made a few changes to resolve those mistakes. Please review them.

}

export default checkLogin;
Loading