Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

341
Vistas
Axios response undefined when function does not find user

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)
      }

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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!'}) 
about 4 years ago · Juan Pablo Isaza Denunciar

0

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?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda