https://github.com/prabaprakash/react-redux-flow-in-depth
Cute Redux Flow in a single JS file
https://github.com/prabaprakash/react-redux-flow-in-depth
react react-redux redux state-management
Last synced: 8 months ago
JSON representation
Cute Redux Flow in a single JS file
- Host: GitHub
- URL: https://github.com/prabaprakash/react-redux-flow-in-depth
- Owner: prabaprakash
- Created: 2018-09-18T17:10:48.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2018-09-19T08:09:48.000Z (about 7 years ago)
- Last Synced: 2025-03-25T08:20:55.614Z (9 months ago)
- Topics: react, react-redux, redux, state-management
- Language: JavaScript
- Homepage: https://codesandbox.io/s/lxxj11qqym
- Size: 3.91 KB
- Stars: 4
- Watchers: 1
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Architecture
```
Observer Pattern + State Pattern
```
# Online Code Sandbox
https://codesandbox.io/s/lxxj11qqym
# Redux Store
```JS
const reducers = (state = {}, action) => {
switch (action.type) {
case "initiate":
return Object.assign({ number: 0 }, state);
case "add":
return Object.assign(state, { number: state.number + 1 });
case "sub":
return Object.assign(state, { number: state.number - 1 });
case "save":
return Object.assign(state, { number: action.number });
}
};
const createStore = (initialState = {}, reducers) => {
let state = initialState;
let listeners = [];
const getState = () => state;
const dispatch = action => {
state = reducers(state, action);
listeners.forEach(listener => listener());
};
const subscribe = listener => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
};
};
return { getState, dispatch, subscribe };
};
var store = createStore({}, reducers);
const unsubscribe = store.subscribe(() => {
console.log(JSON.stringify(store.getState()));
});
store.dispatch({ type: "initiate" });
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
store.dispatch({ type: "add" });
store.dispatch({ type: "sub" });
store.dispatch({ type: "sub" });
//unsubscribe();
store.dispatch({ type: "sub" });
```
# React Component
```JS
import React from "react";
import PropTypes from "prop-types";
import { render } from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
parseInt(e.target.value)
? this.props.dispatch({ type: "save", number: parseInt(e.target.value) })
: "";
}
render() {
return (
this.props.dispatch({ type: "add" })}
/>
this.props.dispatch({ type: "sub" })}
/>
);
}
}
App.propTypes = {
number: PropTypes.number,
dispatch: PropTypes.func
};
```
# Wiring Redux and React
```JS
store.subscribe(() =>
render(
,
document.getElementById("app")
)
);
```