Created
April 20, 2020 09:04
-
-
Save hscstudio/d0d8f8aa091eae0853c7030d638f45d1 to your computer and use it in GitHub Desktop.
Pattern Call Data Pada React Hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
const getUsers = async (callback) => { | |
// call api | |
// dummy response | |
const response = { | |
status: 'success', | |
message: 'get data user success', | |
data: [ | |
{id: 1, name: 'AAA'}, | |
{id: 2, name: 'BBB'}, | |
{id: 3, name: 'CCC'}, | |
], | |
} | |
callback(response) | |
} | |
const addUser = async (name, callback) => { | |
// call api | |
// dummy response | |
const response = { | |
status: 'success', | |
message: 'add data success', | |
data: { id: 4, name: name }, | |
} | |
callback(response) | |
} | |
function ListUser() { | |
const [initial, setIntial] = React.useState(true) | |
const [users, setUsers] = React.useState([]) | |
const [name, setName] = React.useState('') | |
React.useEffect(()=>{ | |
if (initial) { | |
setIntial(false) | |
getUsers( ({status, message, data}) => { | |
if (status === 'success') { | |
setUsers(data) | |
} else { | |
// throw error | |
console.log(message) | |
} | |
}) | |
} | |
}, [initial]) | |
const handleSubmit = (evt) => { | |
evt.preventDefault(); | |
addUser(name, ({status, message, data}) => { | |
if (status === 'success') { | |
console.log('succeess') | |
setUsers([data, ...users]) | |
} else { | |
// throw error | |
console.log(message) | |
} | |
}) | |
} | |
return <> | |
<form onSubmit={handleSubmit}> | |
Name : | |
<input value={name} onChange={e => setName(e.target.value)} /> | |
<button type="submit">ADD</button> | |
</form> | |
{(users && users.length>0) | |
? users.map((user, index) => { | |
return <div key={index}>{user.name}</div> | |
}) | |
: <div> data is empty </div> | |
} | |
</> | |
} | |
export default ListUser |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment