Home > Back-end >  Axios response undefined when function does not find user
Axios response undefined when function does not find user

Time:07-05

Im trying to access error message from express server with redux toolkit. If there is no user found then we send error message with status code.Everything is ok when i use postman, i get error response. But when im trying to access this on Client side, axios response is undefined when i get error.In network tab i stil get error. That leads to redux toolkit reducer not rejecting and me not able to get an error message.

Server controller and service function

controller
....

try {
         
          const user = await findUser({
            ...some values
          });

          //I want this message in redux error message

           if (!user) return res.status(404).send('No user found!') 
          
          const response = await friendService.sendInvitation({...some values});
           
          res.send(response);
        } catch (error) {
          res.status(400).send(error);
        }
...
const findUser=async({id,username})=>{
  
   const user= await users.findOne(...some logic)
   
   
    return user
  }

findUser is returning user if found, if not then its undefined. When i use axios and look for non existing user i get response undefined.But i cant get any error from backend.

Edit
findUser is returning null if user is not found
Redux toolkit slice with call to an api

const api = axios.create({
    baseURL:'http://localhost:4000/api',
    headers:{
        'Content-Type':"application/json"
    },
    withCredentials:true
})

....

 const sendInvitation = createAsyncThunk("friends/sendInvitation", async({ username, shortId }, thunkApi) => {
      try {
        if (!username || !shortId) return;
        const response = await api.post(`/friend/send`, { username, shortId })
          return response;
      } catch (error) {
        console.log(error)
      }

CodePudding user response:

const sendInvitation = createAsyncThunk("friends/sendInvitation", async({ username, shortId }, thunkApi) => {
      try {
        if (!username || !shortId) return;
        const {data} = await api.post(`/friend/send`, { username, shortId })
          return data;
      } catch (error) {
        const message =
  (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
return thunkAPI.rejectWithValue(message);
      }

With your extraReducer,

   .addCase(sendInvitation.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      })

So when the request fails, you send a message in the state, which is achieved from the rejection call

I assume you have an initial state like this

const initialState = {
  data: null,
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

if (!user) return res.status(404).send({message:'No user found!'}) 

CodePudding user response:

Might be a bit of an obvious question but, what datatype does findUser return if the user is not found?

If the return value can be considered in anyway "truthy" the line if (!user) return res.status(404).send('No user found!') wont be evaluated.

Maybe change findUser to return null if no user is found?

  • Related