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

Lab 4 #54

Open
wants to merge 2 commits into
base: practice/start
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
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
{
"name": "swpp-p3-react-tutorial",
"name": "todo",
"version": "0.1.0",
"private": true,
"private": false,
"proxy": "http://127.0.0.1:8000",
"dependencies": {
"@reduxjs/toolkit": "^1.8.5",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.3.0",
"@testing-library/user-event": "13.5.0",
"@types/jest": "27.5.2",
"@types/node": "16.11.56",
"@types/react": "18.0.17",
"@types/react-dom": "18.0.6",
"axios": "^0.27.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.4",
"react-router": "6.3.0",
"react-router-dom": "6.3.0",
"react-scripts": "5.0.1",
"redux": "^4.2.0",
"typescript": "4.7.4",
"web-vitals": "2.1.4"
},
Expand Down
1 change: 0 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ function App() {

export default App;

<div className="TodoList"></div>;
/* actually, it uses className, not class to avoid collision btw JS class
* this syntax is compiled to React.createElement(‘div’, {className: ‘TodoList’})
* by React Transpiler.
Expand Down
5 changes: 5 additions & 0 deletions src/axios/axios_ex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const axios = require('axios');

axios.get('/api/todos')
.then(response => console.log(response))
.catch(error => console.log(error));
11 changes: 8 additions & 3 deletions src/components/Todo/Todo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@ import "./Todo.css";

interface IProps {
title: string;
clicked?: React.MouseEventHandler<HTMLDivElement>; // Defined by React
clickDetail?: React.MouseEventHandler<HTMLDivElement>; // Defined by React
clickDone?: () => void;
clickDelete?: () => void;
done: boolean;
}

const Todo = (props: IProps) => {
return (
<div className="Todo">
<div className={`text ${props.done && "done"}`} onClick={props.clicked}>
<div className={`text ${props.done && "done"}`} onClick={props.clickDetail}>
{props.title}
</div>
{props.done && <div className="done-mark">&#x2713;</div>}
<button onClick={props.clickDone}>{(props.done) ? 'Undone' : 'Done'}</button>
<button onClick={props.clickDelete}>Delete</button>
</div>
);
};
}

export default Todo;
24 changes: 17 additions & 7 deletions src/components/TodoDetail/TodoDetail.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import "./TodoDetail.css";
import {useNavigate, useParams} from "react-router";
import {fetchTodo, selectTodo, todoActions, TodoType} from "../../store/slices/todo";
import {useDispatch, useSelector} from "react-redux";
import {useEffect} from "react";
import {AppDispatch} from "../../store";

type Props = {
title: string;
content: string;
};
const TodoDetail = () => {
const { id } = useParams();
const dispatch = useDispatch<AppDispatch>();

const todoState = useSelector(selectTodo);

useEffect(() => {
dispatch(fetchTodo(Number(id)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);

const TodoDetail = (props: Props) => {
return (
<div className="TodoDetail">
<div className="row">
<div className="left">Name:</div>
<div className="right">{props.title}</div>
<div className="right">{todoState.selectedTodo?.title}</div>
</div>
<div className="row">
<div className="left">Content:</div>
<div className="right">{props.content}</div>
<div className="right">{todoState.selectedTodo?.content}</div>
</div>
</div>
);
Expand Down
15 changes: 12 additions & 3 deletions src/containers/TodoList/NewTodo/NewTodo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ import { useState } from "react";
import { Navigate } from "react-router-dom";
// import { useNavigate } from "react-router-dom";
import "./NewTodo.css";
import {useDispatch} from "react-redux";
import {postTodo, todoActions} from "../../../store/slices/todo";
import {AppDispatch} from "../../../store";

export default function NewTodo() {
const [title, setTitle] = useState<string>("");
const [content, setContent] = useState<string>("");
const [submitted, setSubmitted] = useState<boolean>(false);

const dispatch = useDispatch<AppDispatch>();

// const navigate = useNavigate()
// const postTodoHandler = () => {
// const data = { title: title, content: content };
Expand All @@ -16,10 +21,14 @@ export default function NewTodo() {
// navigate('/todos')
// };

const postTodoHandler = () => {
const postTodoHandler = async () => {
const data = { title: title, content: content };
alert("Submitted\n" + data.title + "\n" + data.content);
setSubmitted(true);
const result = await dispatch(postTodo(data));
console.log(result)
if (result.payload) {
setSubmitted(true); }else{
alert("Error on post Todo");
}
};

if (submitted) {
Expand Down
41 changes: 23 additions & 18 deletions src/containers/TodoList/TodoList.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { useMemo, useState } from "react";
import {useEffect, useMemo, useState} from "react";
import { NavLink } from "react-router-dom";
import Todo from "../../components/Todo/Todo";
import TodoDetail from "../../components/TodoDetail/TodoDetail";
import "./TodoList.css";
import {useDispatch, useSelector} from "react-redux";
import {deleteTodo, fetchTodos, selectTodo, todoActions, toggleDone} from "../../store/slices/todo";
import {useNavigate} from "react-router";
import axios from "axios";
import {AppDispatch} from "../../store";

interface IProps {
title: string;
Expand All @@ -14,37 +19,37 @@ export default function TodoList(props: IProps) {
const { title } = props;
const [selectedTodo, setSelectedTodo] = useState<TodoType | null>(null);

const [todos, setTodos] = useState<TodoType[]>([
{ id: 1, title: "SWPP", content: "take swpp class", done: true },
{ id: 2, title: "Movie", content: "watch movie", done: false },
{ id: 3, title: "Dinner", content: "eat dinner", done: false },
]);

const clickTodoHandler = (td: TodoType) => {
if (selectedTodo === td) {
setSelectedTodo(null);
} else {
setSelectedTodo(td);
}
};
const todoState = useSelector(selectTodo);
const dispatch = useDispatch<AppDispatch>();
const navigate = useNavigate();

const todoDetail = useMemo(() => {
return selectedTodo ? (
<TodoDetail title={selectedTodo.title} content={selectedTodo.content} />
<TodoDetail/>
) : null;
}, [selectedTodo]);

const clickTodoHandler = (td: TodoType) => {
navigate('/todos/' + td.id)
};

useEffect(() => {
dispatch(fetchTodos());
}, []);

return (
<div className="TodoList">
<div className="title">{title}</div>
<div className="todos">
{todos.map((td) => {
{todoState.todos.map((td) => {
return (
<Todo
key={`${td.id}_todo`}
key={td.id}
title={td.title}
done={td.done}
clicked={() => clickTodoHandler(td)}
clickDetail={() => clickTodoHandler(td)}
clickDone={() => dispatch(toggleDone(td.id))}
clickDelete={() => dispatch(deleteTodo(td.id))}
/>
);
})}
Expand Down
5 changes: 4 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {Provider} from "react-redux";
import {store} from "./store";

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);

root.render(
<React.StrictMode>
<App />
<Provider store={store}><App /></Provider>
</React.StrictMode>
);
19 changes: 19 additions & 0 deletions src/redux-basics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { configureStore } = require('@reduxjs/toolkit'); // load module in Node.js
const initialState = { number: 0 }; // default state

const myReducer = (state = initialState, action) => {
if (action.type === 'ADD') { return ({ ...state, number: state.number + 1}); }
else if (action.type === 'ADD_VALUE') {
return ({...state, number: state.number + action.value});
}
return state;
}

const store = configureStore({ reducer: myReducer });

store.subscribe(() => {
console.log('[Subscription]', store.getState());
});

store.dispatch({ type: 'ADD' });
store.dispatch({ type: 'ADD_VALUE', value: 5 });
11 changes: 11 additions & 0 deletions src/store/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import todoReducer from "./slices/todo";

// src/store/index.ts
import { configureStore } from "@reduxjs/toolkit";

export const store = configureStore(
{ reducer: {todo: todoReducer}}
); // TODO

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
103 changes: 103 additions & 0 deletions src/store/slices/todo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import {createAsyncThunk, createSlice, PayloadAction} from "@reduxjs/toolkit";
import { RootState } from "..";
import axios from "axios";

export interface TodoType { id: number; title: string; content: string; done: boolean; }
export interface TodoState { todos: TodoType[]; selectedTodo: TodoType | null; }
const initialState: TodoState = {
todos: [
{ id: 1, title: "SWPP", content: "take swpp class", done: true },
{ id: 3, title: "Dinner", content: "eat dinner", done: false },
], selectedTodo: null,
}; // continue

export const todoSlice = createSlice({
name: "todo",
initialState,
reducers: {
getAll: (state, action: PayloadAction<{ todos: TodoType[] }>) => {},
getTodo: (state, action: PayloadAction<{ targetId: number }>) => {
const target = state.todos.find((td) => td.id === action.payload.targetId);
state.selectedTodo = target ?? null
},
toggleDone: (state, action: PayloadAction<{ targetId: number }>) => {
const todo = state.todos.find(
(value) => value.id === action.payload.targetId
);
if (todo) {
todo.done = !todo.done;
} },
deleteTodo: (state, action: PayloadAction<{ targetId: number }>) => {
const deleted = state.todos.filter((todo) => {
return todo.id !== action.payload.targetId;
});
state.todos = deleted;
},
addTodo: (
state,
action: PayloadAction<{ title: string; content: string }> )=>{
const newTodo = {
id: state.todos[state.todos.length - 1].id + 1, // temporary
title: action.payload.title,
content: action.payload.content,
done: false,
};
state.todos.push(newTodo);
},
},
extraReducers: (builder) => {
builder.addCase(fetchTodos.fulfilled, (state, action) => {
state.todos = action.payload;
});
builder.addCase(postTodo.rejected, (_state, action) => {
console.error(action.error);
});
builder.addCase(fetchTodo.fulfilled, (state, action) => {
state.selectedTodo = action.payload;
});
},
});

export const fetchTodo = createAsyncThunk( "todo/fetchTodo",
async (id: TodoType["id"], { dispatch }) => {
const response = await axios.get(`/api/todo/${id}/`);
return response.data ?? null;
}
);

export const fetchTodos = createAsyncThunk(
"todo/fetchTodos",
async () => {
const response = await axios.get<TodoType[]>("/api/todo/");
return response.data;
}
);

export const postTodo = createAsyncThunk(
"todo/postTodo",
async (td: Pick<TodoType, "title" | "content">, { dispatch }) => {
const response = await axios.post("/api/todo/", td);
dispatch(todoActions.addTodo(response.data));
return response.data;
}
);

export const deleteTodo = createAsyncThunk(
"todo/deleteTodo",
async (id: TodoType["id"], { dispatch }) => {
await axios.delete(`/api/todo/${id}/`);
dispatch(todoActions.deleteTodo({ targetId: id }));
}
);

export const toggleDone = createAsyncThunk(
"todo/toggleDone",
async (id: TodoType["id"], { dispatch }) => {
await axios.put(`/api/todo/${id}/`);
dispatch(todoActions.toggleDone({ targetId: id }));
}
);

export const todoActions = todoSlice.actions;
export const selectTodo = (state: RootState) => state.todo;
export default todoSlice.reducer;
Loading