I am building a reactjs app
I want to get my user id from redux state
using useSelector and pass it to useEffect
My code
UserReducer
export function userReducer(state = { token: "", user: {} }, action) {
switch (action.type) {
case "LOGIN":
return action.payload;
case "LOGOUT":
return action.payload;
default:
return state;
}
}
ViewTransaction.jsx
const ViewTransaction = () => {
const user_id = useSelector((state) => state.user.user.id);
const params = useParams();
useEffect(() => {
setLoading(true);
PendingServices.getPendingTransaction(
`localhost:8000/user/transaction/pending/get-transaction/${params.id}?user_id=${user_id}`
)
.then((response) => {})
.catch((error) => {})
.finally(() => {
setLoading(false);
});
}, []);
return (
<div>transaction</div>
)
}
export default ViewTransaction;
user_id is showing undefined.
You need to pass user_id in useEffects dependency array and check if its defined or nod... because on first render its undefined because redux didnt provided it yet
useEffect(() => {
if(user_id){
setLoading(true);
PendingServices.getPendingTransaction(
`localhost:8000/user/transaction/pending/get-transaction/${params.id}?user_id=${user_id}`
)
.then((response) => {})
.catch((error) => {})
.finally(() => {
setLoading(false);
});
}
}, [user_id]);
Like Drew wrote in the comment above your dependency array is missing variables. React tries to be smart about not calling hooks in vain, and by passing it no dependencies you let it assume that the call to the method in useEffect will always be the same, and that it can cache and reuse the result of the invocation. Since user_id is undefined initially, when no one have logged in, the result of useEffect with an undefined user is cached.
By adding user_id and params.id in the dep array you're telling React that "each time these variables change, the result of the method should also change", so it will invalidate the cached useEffect result and run the method again.
I'd recommend using this eslint plugin to automatically help catch these cases: https://www.npmjs.com/package/eslint-plugin-react-hooks