1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>ReactJS</title> <style> table { border-collapse: collapse; } th, td { padding: 0 0.5rem; border: 1px solid black; } </style> </head> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.0/redux.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.4/react-redux.js"></script> <script src="https://cdn.jsdelivr.net/npm/@reduxjs/[email protected]/dist/redux-toolkit.umd.min.js"></script> <!-- =========== src/utils.js =========== --> <script> class Uuid { s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } s16() { return this.s4() + this.s4() + this.s4() + this.s4(); } } let uuid = new Uuid(); </script> <!-- =========== slices/listStudent_slice.js =========== --> <script> //Dùng RTK.createSlice khai báo tất cả State, Reducers và Actions luôn let listStudent_local = JSON.parse(localStorage.getItem('listStudent')) || { data: [], loading: false }; const listStudent_slice = RTK.createSlice({ name: 'listStudent', initialState: listStudent_local, reducers: { action_saveStudent(state, action) { if (!action.payload.id) { let new_student = { id: uuid.s16(), username: action.payload.username, email: action.payload.email, }; state.data.push(new_student); } else { let find_student = state.data.find((item) => item.id == action.payload.id); find_student.username = action.payload.username; find_student.email = action.payload.email; } localStorage.setItem('listStudent', JSON.stringify(state)); return state; }, action_deleteStudent(state, action) { state.data = state.data.filter((item) => item.id != action.payload); localStorage.setItem('listStudent', JSON.stringify(state)); return state; }, action_setListStudent(state, action) { state.data = action.payload.map(item => ({ username: item.username, email: item.email, id: item.id, })) state.loading = false; localStorage.setItem('listStudent', JSON.stringify(state)); return state; }, action_getListStudentsOnline(state, action) { state.loading = true; return state; } } }); // export ra các actions, reducer tương ứng :D const { action_saveStudent, action_deleteStudent, action_setListStudent, action_getListStudentsOnline } = listStudent_slice.actions; const listStudent_reducer = listStudent_slice.reducer; </script> <!-- =========== src/api/studentAPI =========== --> <script type="text/babel"> //API cần để riêng 1 file const getStudentsFake = (url) => async (dispatch) => { dispatch(action_getListStudentsOnline()); let response = await fetch(url); let responseJSON = await response.json(); dispatch(action_setListStudent(responseJSON)); } </script> <!-- =========== src/store.js =========== --> <script type="text/babel"> //Khai báo tất cả các Reducer trong store ở dưới đây //ReduxToolkit đã cài đặt sẵn middlewareThunk và Redux devtools extension rồi, ko cần cài đặt gì thêm nữa const store = RTK.configureStore({ reducer: { listStudent: listStudent_reducer, //product: product_reducer, } }) </script> <!-- =========== components/App.js =========== --> <script type="text/babel"> function App(props) { //Sử dụng useSelector và useSelector của useDispatch sẽ tiện hơn rất nhiều so với phải dùng HOC const listStudent = ReactRedux.useSelector(state => state.listStudent); const dispatch = ReactRedux.useDispatch(); const dispatch_saveStudent = (student) => dispatch(action_saveStudent(student)); const dispatch_deleteStudent = (id) => dispatch(action_deleteStudent(id)); const dispatch_getStudentsFake = (url) => dispatch(getStudentsFake(url)); const [url_fakeStudent, setUrl_fakeStudent] = React.useState('https://jsonplaceholder.typicode.com/users') const [filterName, setFilterName] = React.useState(''); const [student, setStudent] = React.useState({ username: '', email: '', id: '' }); const updateState_student = (e) => { let newStudent = { ...student }; newStudent[e.target.name] = e.target.value; setStudent(newStudent) }; const onSaveStudent = (e) => { if (!student.username || !student.email) return; dispatch_saveStudent(student); setStudent({ username: '', email: '', id: '' }); }; return ( <div> <button onClick={() => { setStudent({ username: '', email: '', id: '' }) }}>New Student</button> <br /> <input type="text" placeholder="username" name="username" value={student.username} onChange={updateState_student} /> <br /> <input type="text" placeholder="email" name="email" value={student.email} onChange={updateState_student} /> <br /> <button onClick={onSaveStudent}> {student.id ? 'Update Student' : 'Add Student'} </button> <br /> <br /> <input type="text" placeholder="Search ..." name="txtFilterName" value={filterName} onChange={(e) => { setFilterName(e.target.value) }} /> <table> <thead> <tr> <th>#</th> <th>Username</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> { listStudent.data .filter((item) => item.username.includes(filterName)) .map((item, index) => { return ( <tr key={item.id}> <td>{index}</td> <td>{item.username}</td> <td>{item.email}</td> <td> <button onClick={(e) => { setStudent({ ...item }) }}>Sửa</button> <button onClick={(e) => { dispatch_deleteStudent(item.id) }}>Xóa</button> </td> </tr> ); }) } </tbody> </table> <select value={url_fakeStudent} onChange={(e) => { setUrl_fakeStudent(e.target.value) }}> <option value="https://jsonplaceholder.typicode.com/users">https://jsonplaceholder.typicode.com/users</option> <option value="https://fakestoreapi.com/users?limit=10">https://fakestoreapi.com/users?limit=10</option> </select><br /> <button onClick={e => { dispatch_getStudentsFake(url_fakeStudent) }}>Get Student Fake</button> {listStudent.loading && <img src="https://vcdn-ione.vnecdn.net/2016/07/13/loading-256-0001-4566-1468383063.gif" width="14px" />} </div> ); } </script> <!-- =========== src/index.js =========== --> <script type="text/babel"> //Connect React và Redux bằng Provider, với store=store đã được khai báo ở trên const Provider = ReactRedux.Provider; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); </script> </body> </html> |
Demo-CRUD: 4. ListStudent with Redux-Toolkit
Author: admin - Posted: 29/06/21 - Update: 29/06/21