I am trying to develop a React application that shows a list of items using Hooks but an infinite loop is happening. I think the state is not being identified as updated but I cannot tell why.
I have seen at the documentation that it could be the dependencies that I should add on the useEffect function, but when I remove the dependencies on useEffect it solves the problem. Moreover this is not what the documentation recommends to do, they recommend to put all dependencies on the list.
The codesandbox is here: https://codesandbox.io/s/react-listing-forked-6sd99 and if I uncomment the line 30 at Dashboard.ts it is possible to see the infinite loop, this is the line that calls the dispatch function (and also codesandbox will freeze for some seconds).
The useSelector and useEffect functions are as below, located at the Dashboard.tsx file:
const catalog = useSelector<RootState, MetricState>(
(state) => state.fetchMetrics
);
console.log(catalog);
const dispatch = useDispatch();
const classes = useStyles();
useEffect(() => {
// dispatch(appReducer.actionCreators.fetchMetrics());
},[catalog, dispatch]));
The mocked data is as below, on the apiCreators.js file
export function fetchMetrics() {
const action = {
type: ACTION_TYPES.FETCH_METRICS,
payload: []
};
return fetchMetricsCall(action);
const fetchMetricsCall = (action) => async (dispatch) => {
try {
dispatch({
type: action.type,
payload: {
metrics: [
{
name: "one",
owner: {
team: "test"
}
},
{
name: "one",
owner: {
team: "test"
}
}
] //contains the data to be passed to reducer
}.metrics
});
} catch (e) {
dispatch({
type: ACTION_TYPES.FAILURE,
payload: console.log(e) //TODO: fix return type
});
}
};