I'm currently trying to implement a GET request inside a Redux reducer and use the result inside a React functional component, here's what I have so far:
My Users.tsx reducer (Only the relevant call, the rest of the file is the standard format you'd expect from a reducer):
export function getUsers() {
return(dispatch: any) => {
dispatch(requestUsers());
fetch("https://reqres.in/api/users")
.then(res => res.json())
.then(
(result) => {
dispatch(receiveUsers(result));
}
)
}
}
And here's my functional component:
export const Home: React.FC = () => {
const dispatch = useDispatch();
const userList: UserData = useSelector((state: any) => state.users.users);
console.log("rendered", userList);
useEffect(() => {
dispatch(getUsers());
}, [])
return (
<IonContent>
{userList && (userList.data.map((user) => (
<IonCard key={user.id}>
<IonCardHeader>
<IonCardTitle className="ion-text-center">{user.first_name} {user.last_name}</IonCardTitle>
</IonCardHeader>
<IonCardContent className="ion-text-center">
<p>{user.email}</p>
</IonCardContent>
</IonCard>
)))
}
</IonContent>
)
}
export default Home;
It is working right now but the component is rendered 3 times (2 with userList undefined) as opposed from the 2 I'd expect (Once when the component is first loaded and once after the user info is received), is this normal behaviour? Otherwise why does the third render happen?
What I'm trying to achieve is a functional component that uses a Redux dispatch function to call an API and then render after the results are in, is this the correct way to implement it?