Reputation: 1199
In my react/redux app, i have an action that gets called to retrieve data from state in redux each time the component is mounted. My way does not work
Below is the error I'm getting:
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps
Here is my code:
import { getInvoiceData } from "../../actions/tables"
const TableSection = (props) =>{
useEffect(() => {
props.getInvoiceData();
}, []);
const classes = useStyles();
(...)
TableSection.propTypes = {
invoiceData: PropTypes.object
};
const mapStateToProps = (state) => ({
invoiceData: state.tables.invoiceData,
});
export default connect(mapStateToProps, { getInvoiceData })(TableSection);
Upvotes: 3
Views: 6278
Reputation: 3507
using react-redux hooks like useSelector
and useDispatch
will minimize your work time, here your code with react-redux hooks:
import { getInvoiceData } from "../../actions/tables"
import {useSelector ,useDispatch} from "react-redux"
const TableSection = (props) =>{
const {invoiceData} = useSelector(state=>state.tables)
const dispatch = useDispatch()
useEffect(() => {
dispatch(getInvoiceData())
}, []);
const classes = useStyles();
return (<div>
{// here do something with invoiceData}
{invoiceData && invoiceData.map(...)}
</div>)
}
TableSection.propTypes = {
invoiceData: PropTypes.object
};
export default TableSection;
Upvotes: 3
Reputation: 1588
The dependency array you pass to useEffect()
is empty, but you're using props. getInvoiceData()
inside of it, so it's missing the props
. Add it like this:
useEffect(() => {
props.getInvoiceData();
}, [props]);
Better would be to deconstruct your props:
const TableSection = ({invoiceData , getInvoiceData}) =>{
useEffect(() => {
getInvoiceData();
}, [getInvoiceData]);
// Use invoiceData here
console.log(invoiceData);
Dependencies are used to let useEffect()
know if it should fire again or not. Since your getInvoiceData
is function, in this case it will only fire once, just like componentDidMount()
.
Upvotes: 4