Reputation: 5968
I am new to redux hooks and react hooks and this is my code that doesn't stop rendering?
const App: React.FC = () => {
const dispatch = useDispatch();
const [page, setPage] = useState(1);
const fetchUsers = async (page: number) => {
dispatch({
type: FETCH_USERS_REQUEST,
payload: { page }
});
try {
const { data, ...result } = await api.fetchUsers(page);
const user = new schema.Entity('data');
const users = normalize(
{ users: data },
{
users: [user]
}
);
dispatch({
type: FETCH_USERS_SUCCESS,
payload: {
...result,
users
}
});
} catch (error) {
dispatch({ type: FETCH_USERS_FAILURE, payload: { error } });
}
};
useEffect(() => {
fetchUsers(1);
}, [fetchUsers]);
const users = useSelector((state: RootState) => state.users);
console.log('asd', users);
return (
<div className="vh-100 vw-100">
<header>Users</header>asdasd
</div>
);
};
fetchUsers is an async method that i plan to use multiple times on loadMore and pagination, however, this is not working, how do i make it work?
Upvotes: 0
Views: 483
Reputation: 2267
Your fetchUsers is changing on each rerender that is casing your useEffect with that fetch to trigger.
Try this:
useEffect(() => {
fetchUsers(pageNumber);
}, [pageNumber]);
Upvotes: 2