Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import React, { useState } from 'react';
  2.  
  3. import { createStore } from 'redux';
  4.  
  5. const store = createStore(reducer);
  6.  
  7. function useCount() {
  8. const [count, setCount] = useState(store.getState().count);
  9.  
  10. store.subscribe(() => {
  11. setCount(store.getState().count);
  12. });
  13.  
  14. return count;
  15. };
  16.  
  17. function useSetCount() {
  18. return store.dispatch;
  19. };
  20.  
  21. const initialState = {
  22. count: 0
  23. };
  24.  
  25. function reducer(state = initialState, action) {
  26. switch (action.type) {
  27. case 'increment':
  28. return {
  29. count: state.count + 1
  30. };
  31. case 'decrement':
  32. return {
  33. count: state.count - 1
  34. };
  35. case 'reset':
  36. return {
  37. count: 0
  38. };
  39. default:
  40. return state;
  41. };
  42. };
  43.  
  44. const App = () => (
  45. <>
  46. <CountDisplay />
  47. <div>
  48. <IncreaseCountButton />
  49. <DecreaseCountButton />
  50. <ResetCountButton />
  51. </div>
  52. </>
  53. );
  54.  
  55. function CountDisplay() {
  56. const count = useCount();
  57.  
  58. return (
  59. <>
  60. <h1>The current count state:</h1>
  61. <p>{count}</p>
  62. </>
  63. );
  64. };
  65.  
  66. function UpdateCountButton({children, onClick}) {
  67. return <button onClick={onClick}>{children}</button>;
  68. };
  69.  
  70. function IncreaseCountButton() {
  71. const setCount = useSetCount();
  72.  
  73. function increment() {
  74. setCount({ type: 'increment' });
  75. };
  76.  
  77. return <UpdateCountButton onClick={increment}>+</UpdateCountButton>;
  78. };
  79.  
  80. function DecreaseCountButton() {
  81. const setCount = useSetCount();
  82.  
  83. function decrement() {
  84. setCount({ type: 'decrement' });
  85. };
  86.  
  87. return <UpdateCountButton onClick={decrement}>-</UpdateCountButton>;
  88. };
  89.  
  90. function ResetCountButton() {
  91. const setCount = useSetCount();
  92.  
  93. function reset() {
  94. setCount({ type: 'reset' });
  95. };
  96.  
  97. return <UpdateCountButton onClick={reset}>reset</UpdateCountButton>;
  98. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement