Last active
June 30, 2021 03:52
-
-
Save ilyas-shah/4ef3f6cacfecc952dd33cd78acd85773 to your computer and use it in GitHub Desktop.
Example: Data fetching in React component using Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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