add example of async API request and action

This commit is contained in:
Sanjay Bhangar 2018-12-01 21:40:41 +05:30
parent f6da07ed0c
commit 5517141edf
5 changed files with 73 additions and 3 deletions

View File

@ -0,0 +1,48 @@
import config from '../config';
function fetchVideos() {
console.log('fetchVideos called');
return dispatch => {
console.log('inside dispatch function');
dispatch(startLoadingVideos());
const params = {
"keys":["editable","modified","title","source","project","topic","language","duration","id"],
"query": {
"conditions":[],
"operator":"&"
},
"range":[0,100],
"sort": [{"key":"title","operator":"+"}]
};
let formData = new FormData();
formData.append('action', 'find');
formData.append('data', JSON.stringify(params));
fetch(config.apiUrl, {
method: 'POST',
// headers: {
// "Content-Type": "application/x-www-form-urlencoded"
// },
body: formData
})
.then(response => response.json())
.then(json => {
dispatch(receiveVideos(json.data.items));
});
}
}
function startLoadingVideos() {
return {
type: 'START_LOADING_VIDEOS'
}
}
function receiveVideos(videos) {
return {
type: 'RECEIVE_VIDEOS',
payload: videos
}
}
export default fetchVideos;

View File

@ -0,0 +1,3 @@
export default {
apiUrl: 'https://858.ma/api'
};

View File

@ -2,6 +2,7 @@ import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import testAction from '../actions/test';
import fetchVideos from '../actions/fetchVideos';
class Home extends React.Component {
clickBtn() {
@ -17,6 +18,13 @@ class Home extends React.Component {
</div>
<div>
<button onClick={ this.clickBtn.bind(this) }>Click me</button>
<button onClick={ this.props.fetchVideos }>Fetch videos</button>
</div>
<div>
{ this.props.loading && 'Loading...'}
{ this.props.videos.map(video => {
return (<div ref={ video.id }>{ video.title }</div>);
})}
</div>
</div>
);
@ -24,11 +32,14 @@ class Home extends React.Component {
}
const mapStateToProps = state => ({
test: state.home.test
test: state.home.test,
loading: state.home.loading,
videos: state.home.videos
});
const mapDispatchToProps = dispatch => ({
testAction: value => dispatch(testAction(value))
testAction: value => dispatch(testAction(value)),
fetchVideos: () => dispatch(fetchVideos())
});
export default connect(mapStateToProps, mapDispatchToProps)(Home);

View File

@ -4,6 +4,12 @@ export default function (state = {}, action) {
switch (action.type) {
case 'TEST_ACTION':
return Object.assign({}, state, { test: action.payload });
case 'START_LOADING_VIDEOS':
return Object.assign({}, state, { loading: true });
case 'RECEIVE_VIDEOS':
return Object.assign({}, state, { loading: false, videos: action.payload })
}
return state;

View File

@ -5,7 +5,9 @@ import rootReducer from '../reducers';
// Add initial state here
const initialState = {
'home': {
'test': 'foo'
'test': 'foo',
'loading': false,
'videos': []
}
};