Skip to content

Commit

Permalink
React Hooks with Flux
Browse files Browse the repository at this point in the history
  • Loading branch information
dachi023 committed Feb 26, 2019
1 parent 0f5ebfd commit 2c4fe31
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 26 deletions.
42 changes: 16 additions & 26 deletions react-hooks-with-flux/src/App.js
@@ -1,28 +1,18 @@
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import React, { useReducer } from 'react'
import Counter from './Counter'
import CounterContext from './contexts/CounterContext'
import CounterReducer from './reducers/CounterReducer'
import './App.css'

class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default function App() {
const [state, dispatch] = useReducer(CounterReducer, { count: 0 })
return (
<div className="App">
<header className="App-header">
<CounterContext.Provider value={{ ...state, dispatch }}>
<Counter />
</CounterContext.Provider>
</header>
</div>
)
}

export default App;
14 changes: 14 additions & 0 deletions react-hooks-with-flux/src/Counter.js
@@ -0,0 +1,14 @@
import React, { useContext } from 'react'
import CounterContext from './contexts/CounterContext'
import { increment, decrement } from './actions/CounterActions'

export default function Counter() {
const { count, dispatch } = useContext(CounterContext)
return (
<>
<h2>{count}</h2>
<button onClick={() => increment(dispatch)}>Increment</button>
<button onClick={() => decrement(dispatch)}>Decrement</button>
</>
)
}
13 changes: 13 additions & 0 deletions react-hooks-with-flux/src/actions/CounterActions.js
@@ -0,0 +1,13 @@
export function increment(dispatch) {
dispatch({
type: 'increment',
payload: {}
})
}

export function decrement(dispatch) {
dispatch({
type: 'decrement',
payload: {}
})
}
6 changes: 6 additions & 0 deletions react-hooks-with-flux/src/contexts/CounterContext.js
@@ -0,0 +1,6 @@
import { createContext } from 'react'

export default createContext({
count: 0,
dispatch: null
})
10 changes: 10 additions & 0 deletions react-hooks-with-flux/src/reducers/CounterReducer.js
@@ -0,0 +1,10 @@
export default function CounterReducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 }
case 'decrement':
return { count: state.count - 1 }
default:
return state
}
}

0 comments on commit 2c4fe31

Please sign in to comment.