Skip to content

Instantly share code, notes, and snippets.

@akabab
Last active June 18, 2018 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akabab/3b43c8069b762c7ffb1a530414ae6d01 to your computer and use it in GitHub Desktop.
Save akabab/3b43c8069b762c7ffb1a530414ae6d01 to your computer and use it in GitHub Desktop.
Redux exemple
import React, { Component } from 'react'
import store from './store.js'
class App extends Component {
componentDidMount() {
// subscribe to changes -> forceUpdate will ask React to re-render the view
this.unsubscribe = store.subscribe(() => this.forceUpdate())
}
componentWillUnmount() {
// when component is removed from the view -> remove the subscription
this.unsubscribe()
}
render() {
const state = store.getState()
return (
<div className="App">
<span>Counter: {state.counter}</span>
<button onClick={() => store.dispatch({ type: 'INCREMENT_COUNTER' })}>Increment</button>
<button onClick={() => store.dispatch({ type: 'INCREMENT_COUNTER_BY_N', n: 10 })}>Increment by 10</button>
</div>
)
}
}
const initialState = {
counter: 0
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT_COUNTER': {
return {
...state,
counter: counter + 1
}
}
case 'INCREMENT_COUNTER_BY_N': {
return {
...state,
counter: counter + action.n // n is passed through the action object
}
}
default: return state
}
}
export default reducer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment