Skip to content

Instantly share code, notes, and snippets.

@vidux
Last active January 4, 2020 19:21
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 vidux/e6475c6830e617f0540e49a06fb61739 to your computer and use it in GitHub Desktop.
Save vidux/e6475c6830e617f0540e49a06fb61739 to your computer and use it in GitHub Desktop.
fast include redux-saga to react

Start your react-redux-saga app without headache.

note: npm packages can be Change/Deprecate with time.

main files reducers.js, store.js and store.js

folder structure

you can cusomize any time

───src
   ├───redux
   │        reducers.js
   │        store.js
   │        sagas.js
   │      └─── my_sub_redux_folder
   │            action.js
   │            saga.js
   │            reducer.js
   ├───view
   │   └───getdata
   |        Getdataview.js
   |
    index.js
    app.js

packages list (npm i):

  • redux-saga
  • redux
  • history
  • immutable
  • react-router-dom
  • react-redux
  • connected-react-router
  • redux-thunk

License

MIT

N|Solid

//src/redux/my_sub_redux_folder/action.js
const actions = {
GET_DATA_FETCH_START: 'GET_DATA_FETCH_START',
GET_DATA_FETCH_DONE: 'GET_DATA_FETCH_DONE',
GET_DATA_FETCH_ERROR: 'GET_DATA_FETCH_ERROR',
getDataJson: (data) => {
return (dispatch, getState) => {
dispatch({
type: actions.GET_DATA_FETCH_START,
payload: data
});
};
},
};
export default actions;
//src/app.js
import React, { Component } from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import { store, history } from './redux/store';
// import { renderRoutes } from 'react-router-config';
import './App.scss';
const loading = () => <div className="animated fadeIn pt-3 text-center">Loading...</div>;
// Containers
const DefaultLayout = React.lazy(() => import('./containers/DefaultLayout'));
// Pages
class App extends Component {
render() {
return (
<Provider store={store}>
<HashRouter>
<React.Suspense fallback={loading()}>
<Switch>
<Route path="/" name="Home" render={props => <DefaultLayout {...props}/>} />
</Switch>
</React.Suspense>
</HashRouter>
</Provider>
);
}
}
export default App;
//src/view/getdata/Getdataview.js
import React, { Component,} from 'react';
import { connect } from 'react-redux';
import actions from '../../redux/my_sub_redux_folder/actions';
const { getDataJson } = actions;//import any method from action file
class Getdataview extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
this.props.getDataJson(); //calling action file method
}
render() {
return (
<div className="animated fadeIn">
<p>{(this.props.json_data || {}).subkeyname}</p>
</div>
);
}
function mapStateToProps(state) {
return { ...state.my_reducer.toJS() }; //same name you put in root reducer file
}
export default connect(mapStateToProps, { getDataJson })(Getdataview);
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
//src/redux/my_sub_redux_folder/reducer.js
import { Map } from 'immutable';
import actions from './actions';
const initState = new Map({
});
export default function reducer(state = initState, action) {
switch (action.type) {
case actions.GET_DATA_FETCH_START:
return state
.set('loading', true);
case actions.GET_DATA_FETCH_DONE:
return state
.set('json_data', action.payload)
.set('loading', false);
case actions.GET_DATA_FETCH_ERROR:
return state
.set('json_data', {})
.set('loading', false);
default:
return state;
}
}
//src/redux/reducers.js
import my_reducer from './my_sub_redux_folder/reducer';
export default {
my_reducer,
};
//src/redux/my_sub_redux_folder/saga.js
import { all, takeEvery, fork,call ,put} from 'redux-saga/effects';
import actions from './actions';
import axios from 'axios';
export function* getNasaAstroidJson() {
yield takeEvery(actions.GET_DATA_FETCH_START, function*(payload) {
const Result = yield call(async ()=>
await axios.get(`https://myapi.example.com/getjsondata`)
.then(res => res.data)
);
if (Result.date && Result.hdurl) {
yield put({ type: actions.GET_DATA_FETCH_DONE, payload:Result})
} else {
yield put({ type: actions.GET_DATA_FETCH_ERROR })
}
});
}
export default function* rootSaga() {
yield all([fork(getNasaAstroidJson)]);
}
//src/redux/sagas.js
import { all } from 'redux-saga/effects';
import my_saga from './my_sub_redux_folder/saga';
export default function* rootSaga(getState) {
yield all([
my_saga(),
]);
}
//src/redux/store.js
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { createBrowserHistory } from 'history';
import { routerMiddleware ,connectRouter} from 'connected-react-router';
import thunk from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import reducers from '../redux/reducers';
import rootSaga from '../redux/sagas';
const history = createBrowserHistory();
const sagaMiddleware = createSagaMiddleware();
const routeMiddleware = routerMiddleware(history);
const middlewares = [thunk, sagaMiddleware, routeMiddleware];
const store = createStore(
combineReducers({
...reducers,
router: connectRouter(history),
}),
compose(applyMiddleware(...middlewares))
);
sagaMiddleware.run(rootSaga);
export { store, history };
//-----------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment