Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

333
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda