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 the useEffect
's dependency array and check if it's defined or not. Because on first render it's undefined because redux didn't 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]);