Skip to content

Instantly share code, notes, and snippets.

@ilyas-shah
Last active June 30, 2021 03:52
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 ilyas-shah/4ef3f6cacfecc952dd33cd78acd85773 to your computer and use it in GitHub Desktop.
Save ilyas-shah/4ef3f6cacfecc952dd33cd78acd85773 to your computer and use it in GitHub Desktop.
Example: Data fetching in React component using Redux
import React, {useEffect} from 'react';
import {connect} from 'react-redux';
// React Component
const A = props => {
useEffect(() => {
// fetch data from a remote server
props.fetchData()
}, [props]);
return (
<div>{props?.data}</div>
)
}
const mapStateToProps = state => {data: state?.data};
connect(mapStateToProps, {fetchData})(A);
export {A};
// Action function
const fetchData = async (...arguments) => {
return dispatch => {
try {
// API call
const data = await getData(arguments);
dispatch({type: 'DATA_RECEIVED', data});
} catch (e) {
console.log(e);
dispatch({type: 'ERROR'});
}
}
}
// Reducer function
const reducerA = (state={}, action) => {
switch(action.type) {
case 'DATA_RECEIVED':
return {
state,
...action.payload
}
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment