Skip to content

Instantly share code, notes, and snippets.

@aGuyNamedJonas
Last active June 13, 2017 19:01
Show Gist options
  • Save aGuyNamedJonas/095bf4d332f9b90bb0be62544c456066 to your computer and use it in GitHub Desktop.
Save aGuyNamedJonas/095bf4d332f9b90bb0be62544c456066 to your computer and use it in GitHub Desktop.
Simple slim-redux-react counter example
import React from 'react';
import ReactDOM from 'react-dom';
import { createSlimReduxStore } from 'slim-redux';
import { slimReduxReact, Provider } from 'slim-redux-react';
// STEP #1: Create the slim redux store
// This creates a redux store with the slim-redux functionality injected and the internal reducer initialized
// Parameters: initialState (0), existingRootReducer(null), middleware(redux-devtools browser extension)
const store = createSlimReduxStore(0, null, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
// STEP #2: Create our counter component (just the presentational part)
// In our case it's a stateless functional component, it could also be a statefull or a pure component!
const Counter = (props) => (
<div>
<h1>Current Counter: {props.counter}</h1>
<button onClick={e => props.decreaseCounter()}>-</button>
<button onClick={e => props.increaseCounter()}>+</button>
</div>
)
// STEP #3: Create the change trigger definitions
// You would usually define these in a separated file
const counterChangeTriggers = {
// All we need to know in one place...
increaseCounter: {
// ...Action type (which will show up like that in your devtools)...
actionType: 'INCREMENT',
// ...and the reducer code which will be applied by slim-redux's internal reducer
reducer: (state) => {
return state + 1;
}
// ...and optionally payload validation! (more on that later)
},
decreaseCounter: {
actionType: 'DECREMENT',
reducer: (state) => {
return state - 1;
}
}
};
// Step #4: Create the container component for the counter
const CounterContainer slimReduxReact({
component: Counter,
// subscriptions are a direct mapping:
// propsName: 'state.attributeOfState.subAttributeOfState'
// e.g.: subscriptions: { completedTodos: 'state.todos.completed' }
subscriptions: { counter: 'state'},
// Take a look at counterChangeTriggers again:
// This statement maps the INCREMENT change trigger to props.increaseCounter and DECREMENT to props.decreaseCounter
changeTriggers: counterChangeTriggers,
});
// Step #5: Render...
ReactDOM.render(
<div>
<Provider store={store}>
<CounterContainer/>
</Provider>
</div> ,
document.getElementById('root')
);
@LeftyBC
Copy link

LeftyBC commented Jun 13, 2017

const CounterContainer slimReduxReact({ - should this have an = in it somewhere? Still wrapping my head around using const objects as react components.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment