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

week3 done #32

Open
wants to merge 2 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
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"extends": ["next/babel", "next/core-web-vitals"]
"extends": ["next", "next/core-web-vitals"]
}
36 changes: 31 additions & 5 deletions components/AddTask.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,43 @@
import { useState } from "react"
import axios from "../utils/axios";
import { useAuth } from "../context/auth"
import {toast} from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

export default function AddTask() {
const [newtodo,setNewTodo]=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.
*/

const dataToPost={
"title": newtodo
}
axios
.post(
'todo/create/',
dataToPost,
{
headers:{
Authorization: 'Token ' + token
}
})
.then((res)=>{
setNewTodo('');
toast.success('Task added succesfully!!',{position:"bottom-right",theme:"colored"});
}).catch((err)=>{
toast.error('Some error Occured!',{position:"bottom-right",theme:"colored"})
console.log(err);
})

}
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'
value={newtodo}
onChange={(e)=>{setNewTodo(e.target.value)}}
/>
<button
type='button'
Expand Down
46 changes: 38 additions & 8 deletions components/LoginForm.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
import router from "next/router";
import {No_Auth_req} from "../middlewares/no_auth_required"
import { useState } from "react";
import { useAuth } from "../context/auth";
import axios from '../utils/axios'
import { toast } from "react-toastify";

export default function RegisterForm() {
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)
*/
No_Auth_req();
const [username,setUserName] = useState("");
const [password,setPassword] = useState("");
const {setToken} = useAuth();
const Login = () => {

if (username === '' || password === '') {
toast.warn('Do not use empty fields!',{position:"top-center",theme:"colored"});
return;
}
const dataForApiRequest = {
username: username,
password: password
}

axios.post(
'auth/login/',
dataForApiRequest,
).then(function({data, status}) {
setToken(data.token);
toast.success('Login was successful!!',{position:"top-center",theme:"colored"})
router.reload();
}).catch(function(err) {
toast.error('Invalid credentials! :(',{position:"top-center",theme:"colored"});
console.log(err);
})
}

return (
Expand All @@ -19,6 +45,8 @@ export default function RegisterForm() {
name='inputUsername'
id='inputUsername'
placeholder='Username'
value={username}
onChange={(event) => setUserName(event.target.value)}
/>

<input
Expand All @@ -27,12 +55,14 @@ export default function RegisterForm() {
name='inputPassword'
id='inputPassword'
placeholder='Password'
value={password}
onChange={(event) => setPassword(event.target.value)}
/>

<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}
onClick={Login}
>
Login
</button>
Expand Down
23 changes: 12 additions & 11 deletions components/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
/* 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 { useState ,useEffect } from 'react'


export default function Nav() {
const { logout, profileName, avatarImage } = useAuth()
const { logout, profileName, avatarImage ,token } = useAuth()
const [tokPresent,settokPresent] = useState(true)

useEffect(()=>{(token)?settokPresent(true):settokPresent(false)},[token])

return (
<nav className='bg-blue-600'>
Expand All @@ -22,19 +23,19 @@ export default function Nav() {
</Link>
</li>
</ul>
<ul className='flex'>
<li className='text-white mr-2'>
<ul className={tokPresent ? 'hideme' :'flex'}>
<li className='text-white mr-5'>
<Link href='/login'>Login</Link>
</li>
<li className='text-white'>
<li className='text-white mr-5'>
<Link href='/register'>Register</Link>
</li>
</ul>
<div className='inline-block relative w-28'>
<div className={tokPresent ?'inline-block relative w-35':'hideme'}>
<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>
<img className='mr-1' src={avatarImage} />
<span className='ml-1 mr-1'>{profileName}</span>
<svg
className='fill-current h-4 w-4'
xmlns='http://www.w3.org/2000/svg'
Expand Down
16 changes: 11 additions & 5 deletions components/RegisterForm.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import React, { useState } from 'react'
import axios from '../utils/axios'
import { useAuth } from '../context/auth'
import { No_Auth_req } from '../middlewares/no_auth_required'
import { useRouter } from 'next/router'
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

export default function Register() {
const { setToken } = useAuth()
No_Auth_req();
const router = useRouter()

const [firstName, setFirstName] = useState('')
Expand All @@ -27,11 +31,11 @@ export default function Register() {
username === '' ||
password === ''
) {
console.log('Please fill all the fields correctly.')
toast.warn('Please fill all the fields correctly.',{position:"top-center",theme:"colored"})
return false
}
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
console.log('Please enter a valid email address.')
toast.warn('Please enter a valid email address.',{position:"top-center",theme:"colored"})
return false
}
return true
Expand All @@ -43,7 +47,7 @@ export default function Register() {
if (
registerFieldsAreValid(firstName, lastName, email, username, password)
) {
console.log('Please wait...')
toast.info('Please wait...',{position:"top-center",theme:"colored"})

const dataForApiRequest = {
name: firstName + ' ' + lastName,
Expand All @@ -58,11 +62,13 @@ export default function Register() {
)
.then(function ({ data, status }) {
setToken(data.token)
toast.success('Registration Successful!!',{position:"top-center",theme:"colored"})
router.push('/')
})
.catch(function (err) {
console.log(
'An account using same email or username is already created'
toast.warn(
'An account using same email or username is already created',
{position:"top-center",theme:"colored"}
)
})
}
Expand Down
93 changes: 68 additions & 25 deletions components/TodoListItem.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,98 @@
/* eslint-disable @next/next/no-img-element */

export default function TodoListItem() {
const editTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Update the dom accordingly
*/
import axios from "../utils/axios";
import { useState } from "react";
import { useAuth } from "../context/auth";
import { API_URL} from "../utils/constants"
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import router from "next/router";


export default function TodoListItem(props) {
const [isEditActive,setEditActive] = useState(false);
const [todo,setTodo] = useState('');
const {token} = useAuth();

const editTask = () => {

setEditActive(true);
}

const deleteTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Send the request to delete the task to the backend server.
* @todo 2. Remove the task from the dom.
*/

axios.delete(
'todo/'+id+'/',
{
headers: {
Authorization: 'Token ' + token,
}
}
).then(()=>{
toast.success('Task Deleted!',{position:"bottom-right",theme:"colored"})
})
.catch((err)=>{
console.log(err);
toast.error('Some error Occured!',{position:"bottom-right",theme:"colored"});
})
}

const updateTask = (id) => {
/**
* @todo Complete this function.
* @todo 1. Send the request to update the task to the backend server.
* @todo 2. Update the task in the dom.
*/

if(token){

axios({
headers : {Authorization : "Token " + token},
url : API_URL + 'todo/' + id + '/',
method : 'patch',
data : {title : todo}
}).then((res)=>{
setEditActive(false)
toast.success('Task updated!',{position:"bottom-right",theme:"colored"})
})
.catch((err)=>{
console.log(err);
toast.error('Some error Occured!',{position:"bottom-right",theme:"colored"});;
})

}
else {
toast.warn('Token not present',{position:"top-center",theme:"colored"});
toast.info('Please login to continue..',{position:"top-center",theme:"colored"})
router.push('/login');
}


}

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-'+props.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={isEditActive?'appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:ring todo-edit-task-input':'hideme'}
placeholder='Edit The Task'
value={todo}
onChange={(e)=>{setTodo(e.target.value)}}
/>
<div id='done-button-1' className='hideme'>
<div id={'done-button-'+props.id} className={isEditActive?'':'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(props.id)}
>
Done
</button>
</div>
<div id='task-1' className='todo-task text-gray-600'>
Sample Task 1
<div id={'task-'+props.id} className={isEditActive ? 'hideme':'todo-task text-gray-600'}>
{props.title}
</div>
<span id='task-actions-1' className=''>
<span id={'task-actions-'+props.id} className={isEditActive?'hideme':''}>
<button
style={{ marginRight: '5px' }}
type='button'
onClick={editTask(1)}
onClick={editTask}
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 @@ -62,7 +105,7 @@ export default function TodoListItem() {
<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)}
onClick={()=> deleteTask(props.id)}
>
<img
src='https://res.cloudinary.com/nishantwrp/image/upload/v1587486661/CSOC/delete.svg'
Expand Down
16 changes: 12 additions & 4 deletions context/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useEffect, useState, useContext, createContext } from 'react'
import { useCookies } from 'react-cookie'
import axios from '../utils/axios'
import { useRouter } from 'next/router'
import {toast} from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

const AuthContext = createContext({})

Expand All @@ -10,13 +12,17 @@ export const AuthProvider = ({ children }) => {
const [profileName, setProfileName] = useState('')
const [avatarImage, setAvatarImage] = useState('#')
const [cookies, setCookies, removeCookies] = useCookies(['auth'])
const token = cookies.token
const token=cookies.token;

const setToken = (newToken) => setCookies('token', newToken, { path: '/' })
const deleteToken = () => removeCookies('token')

const logout = () => {
setProfileName('')
setAvatarImage('#')
deleteToken()
router.push('/login')
toast.info('Logged out!',{position:"top-center",theme:"colored"})
router.reload();
}

useEffect(() => {
Expand All @@ -34,9 +40,11 @@ export const AuthProvider = ({ children }) => {
'&background=fff&size=33&color=007bff'
)
setProfileName(response.data.name)
console.log(token);
})
.catch((error) => {
console.log('Some error occurred')
.catch((err) => {
toast.error('Some error occurred',{position:"top-center",theme:"colored"})
console.log(err);
})
}
}, [setAvatarImage, setProfileName, token])
Expand Down
Loading