Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. /**
  2. * 1.) Context. For lifting our state up to any tree below the Provider.
  3. */
  4. const ActivityContext = createContext()
  5.  
  6. /**
  7. * 2.) Provider. For sharing our state across many render trees.
  8. */
  9. export const ActivityProvider = ({ children }) => {
  10. const [activity, setActivity] = useState([])
  11.  
  12. /**
  13. * @function abort
  14. * @returns {undefined}
  15. */
  16. const abort = useCallback(() => abort(getRecentActivity), [])
  17.  
  18. /**
  19. * @function loadActivity
  20. * @async
  21. * @returns {undefined}
  22. */
  23. const load = useCallback(async () => {
  24. try {
  25. const result = await getRecentActivity()
  26.  
  27. if (!result || !result.ok || !result.body) {
  28. throw new Error('Unable to fetch recent activity.')
  29. }
  30.  
  31. setActivity(result.body.items)
  32. } catch (err) {
  33. log.error(err)
  34. }
  35. }, [])
  36.  
  37. return (
  38. <ActivityContext.Provider value={{ abort, activity, load }}>
  39. {children}
  40. </ActivityContext.Provider>
  41. )
  42. }
  43.  
  44. /**
  45. * 3.) Custom Hook. For consuming the shared state in any component within the Provider.
  46. */
  47. export const useActivity = () => {
  48. const context = useContext(ActivityContext)
  49.  
  50. if (context === undefined) {
  51. throw new Error(`useActivity must be used within a ActivityProvider.`)
  52. }
  53.  
  54. return context
  55. }
  56.  
  57. /**
  58. * 4a.) Use the Provider.
  59. *
  60. * <ActivityProvider>
  61. * <YourComponent />
  62. * <MaybeSomeOtherThing />
  63. * </ActivityProvider>
  64. *
  65. * 4b.) Use the Hook.
  66. *
  67. * const YourComponent = (props) => {
  68. * const { abort, activity, load } = useActivity()
  69. *
  70. * useEffect(() => {
  71. * load()
  72. * return abort
  73. * }, [])
  74. *
  75. * return <ActivityItems items={activity} />
  76. * }
  77. *
  78. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement