Documente Academic
Documente Profesional
Documente Cultură
In this very basic App I have only one button which can make a call to
the NEWS API . This call requests only one news from the CNN channel
-the top one.
src/
components/
App.js
containers/
Button.js
NewsItem.js
Loading.js
actions/
index.js
reducers/
index.js
sagas/
index.js
index.html
index.js
loading_spiner.gif
index.js
);
sagaMiddleware.run(rootSaga);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);
In this file I’ve initialized redux store . This store uses two middlewares
logger and SAGA. Redux-logger tool to inspect in console panel
triggered actions and state of Redux store.
APP.js
import React from 'react';
import Button from '../containers/Button';
import NewsItem from '../containers/NewsItem'
import Loading from '../containers/Loading'
This file is quite simple. It’s shows only three component.In the first
state it’s displays only a button , during a call to API the spinner
appears, and after the response have received <NewsItem /> is being
shown.
Button.js
let Button=({getNews})=>(
<button onClick={getNews}>Press to see news</button>
)
const mapDispatchToProps = {
getNews: getNews,
};
Button = connect(null,mapDispatchToProps)(Button);
actions/index.js
export const getNews = () => ({
type: 'GET_NEWS',
});
Action creator getNews is very simple .It returns an object with only type
of action.
And let a reducer know how to deal with this type of actions.By now
reducer will looks like this :
reducers/index.js
sagas/index.js
function* fetchNews() {
function* actionWatcher() {
yield takeLatest('GET_NEWS', fetchNews)
}
This file is obviously the most complicated one. I guess it looks quite
challenging because of unusual syntax of ES6 GENERATORS like ‘yield’
and ‘*’. We export from this file function rootSaga in which we call
function actionWatcher.
function* actionWatcher() {
yield takeLatest('GET_NEWS', fetchNews)
}
To put it simple it’s like I’m telling SAGA to wait for action ‘GET_NEWS’
to get dispatched. And ones ‘GET_NEWS’ was dispathced to call
fetchNews function. Inside of fetchNews function happens asynchronous
call to API and when request arrived next action { type:
“NEWS_RECEIVED”, json: json.articles, } is dispatched. As you can see
we don’t even need to write action “NEWS_RECEIVED” in
actions/index.js file because it’s fully described here.
By now let reducer know how to deal with this type of actions
“NEWS_RECEIVED”.
reducers/index.js
So this is final code of reducer. Once response from the API call has
received Redux state will have property news which contains json of one
news.
NewsItem.js
NewsItem = connect(mapStateToProps,null)(NewsItem)
export default NewsItem;
Loading.js
import React from 'react';
import { connect } from 'react-redux'
import img from '../loading_spinner.gif'
Loading = connect(mapStateToProps,null)(Loading)
Lavitr/React-Redux-SAGA-tutorial-APP