Last active
August 31, 2019 16:59
-
-
Save revanth0212/1a4c949a70a98aae3cb7f0ed5775692c to your computer and use it in GitHub Desktop.
A sample Hooks component demonstrating Life Cycle Methods Composition.
This file contains 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
function useLikes() { | |
const [likes, setLikes] = useState(0) | |
const [likedByMySelf, setLikedByMySelf] = useState(false) | |
useEffect(() => { | |
fetchLikes().then(({ likes, likedByMySelf }) => { | |
setLikes(likes) | |
setLikedByMySelf(likedByMySelf) | |
}) | |
}, []) | |
const onLike = () => { | |
setLikes(likedByMySelf ? likes - 1 : likes + 1) | |
setLikedByMySelf(!likedByMySelf) | |
} | |
return [likes, likedByMySelf, onLike] | |
} | |
function useComments() { | |
const [comments, setComments] = useState([]) | |
useEffect(() => { | |
fetchComments().then(setComments) | |
}, []) | |
const onComment = comment => { | |
setComments([...comments, comment]) | |
} | |
return [comments, onComment] | |
} | |
function Feed() { | |
const [likes, likedByMySelf, onLike] = useLikes() | |
const [comments, onComment] = useComments() | |
return ( | |
<RenderTheComponent | |
likes={likes} | |
likedByMySelf={likedByMySelf} | |
comments={comments} | |
onComment={onComment} | |
onLike={onLike} | |
/> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment