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 |
<!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> </head> <body> <div id="app"></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 type="text/babel"> const { useState, useEffect, useReducer } = React; //1. Khai báo state const initialUser = { data: {}, error: '' } //2. Khai báo Reducer const userReducer = (state = initialUser, action) => { switch (action.type) { case 'FETCH_USER_SUCCESS': { return { data: action.data, error: '' } } case 'FETCH_USER_FAILED': { return { data: {}, error: 'Lỗi: ' + action.error } } default: return state; } } function App(props) { const [userID, setUserID] = useState(1); const [loading, setLoading] = useState(false); //3. Khai báo hook: useReducer const [user, userDispatch] = useReducer(userReducer, initialUser) //4. Fake API const apiFakeData = async (id) => { try { let url = `https://reqres.in/api/users/${id}`; let response = await fetch(url); if (response.ok) { let responseJSON = await response.json(); userDispatch({ type: 'FETCH_USER_SUCCESS', data: responseJSON.data, }) } else { console.log("Lỗi server"); userDispatch({ type: 'FETCH_USER_FAILED', error: response.status, }) } } catch (error) { console.log("Lỗi kết nối: ", error); userDispatch({ type: 'FETCH_USER_FAILED', error: error.toString() }) } finally { setLoading(false) } } // Giả sử cho setTimeout 500ms để thấy loading... const getUser = (e) => { let id = e.target.value; setUserID(id); setLoading(true); setTimeout(() => { apiFakeData(id) }, 500); } // Khởi động lấy data luôn, rồi lưu lên reducer useEffect(() => { apiFakeData(userID) }, []) return ( <div> <input type="number" value={userID} onChange={getUser} /> {loading ? <p>Loading...</p> : <div><p>{user.error}</p><p>{JSON.stringify(user.data, null, 4)}</p></div>} </div> ) } ReactDOM.render( <App />, document.getElementById('app') ); </script> </body> </html> |
React-GetAPI: 2. StateManager by Reducer and FetchData by Component
Author: admin - Posted: 05/07/21 - Update: 05/07/21