Fetch dog Thunk
by Allie Yu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/6.0.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.3.0/redux-thunk.min.js"></script>
<div id="root"></div>
Babel + JSX
const {Provider, connect} = ReactRedux;
const {createStore, applyMiddleware} = Redux;
const thunk = ReduxThunk.default;
// Reducer
const initialState = {
url: '',
loading: false,
error: false,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'REQUESTED_DOG':
return {
url: '',
loading: true,
error: false,
};
case 'REQUESTED_DOG_SUCCEEDED':
return {
url: action.url,
loading: false,
error: false,
};
case 'REQUESTED_DOG_FAILED':
return {
url: '',
loading: false,
error: true,
};
default:
return state;
}
};
// Action Creators
const requestDog = () => {
return { type: 'REQUESTED_DOG' }
};
const requestDogSuccess = (data) => {
return { type: 'REQUESTED_DOG_SUCCEEDED', url: data.message }
};
const requestDogError = () => {
return { type: 'REQUESTED_DOG_FAILED' }
};
/* Thunk allows you to write action creators that return a function instead of an action.
The thunk can be used to delay the dispatch of an action,
or to dispatch only if a certain condition is met.
The inner function receives the store methods dispatch and getState as parameters. */
const fetchDog = () => {
return (dispatch) => {
dispatch(requestDog());
fetch('https://dog.ceo/api/breeds/image/random')
.then(res => res.json())
.then(
data => dispatch(requestDogSuccess(data)),
err => dispatch(requestDogError())
);
}
};
// Component
class App extends React.Component {
render () {
return (
<div>
<button onClick={() => this.props.dispatch(fetchDog())}>Show Dog</button>
{this.props.loading
? <p>Loading...</p>
: this.props.error
? <p>Error, try again</p>
: <p><img src={this.props.url}/></p>}
</div>
)
}
}
// Store
const store = createStore(
reducer,
applyMiddleware(thunk)
);
const...