Skip to content
Advertisement

How to use UseEffect every time get user and axios?

I use MERN stack and redux. I have two problem and please help me.
1) Every component react I add this:

const user = useSelector( state => state.user );
  useEffect( ()=>{
     dispatch(User_Auth(12)) ; // I write 12 for action work. 
  });

I want to get user data every time if user loginned or not. Is it true? or some idea have?

2) In backend if data current I send using 200 status codes. another variant I send data other status like this:

router.get('/auth', (req, res) => {
    if(req.isAuthenticated()){
        req.user.isAuth = true;
        res.status(200).json(req.user);
    }
    else{
        return res.status(401).json({
            isAuth: false
        });
    }
});

This is my action get User data:

export const User_Auth =   (value) => async (dispatch) => {
    value = value + 0;
    await axios({
        method: "GET",
        url:'http://localhost:3001/api/users/auth',
        withCredentials:true
    })
    .then(res => {
        
        dispatch({type: user_auth, payload: res.data});
    }).catch(error => {
        // console.log("Auth geldim: ", error);
    });
}

I want if cannot see errors in console.log browser. Can I do that? Thanks

Advertisement

Answer

If you want to see the status code from an error you have to access it like this

error.status

And to get the message

error.message
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement