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

118
Visualizações
React.js Trying to access the response of an API fetch that works and returns data in my /api but I cannot access in my /src/

I think I am probably missing something pretty simple.

in src/api/index.js I have the following:

  export async function loginUser(username, password) {
    try {
      const response = await fetch(`${BASE}/users/login`, {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
           body: JSON.stringify({
             user: {
               username: username,
               password: password
             }
           })
        })
        .then(response => response.json())
        .then(result => {console.log(result)
          const key = result.data.token
          localStorage.setItem('stToken', JSON.stringify(key))
          localStorage.setItem('username', JSON.stringify(username))
        })

          
      
        return response
      
    } catch (error) {
      console.log(error);
    }
  }

My loginUser is being called in my onSubmit handler in my src/component/login.js

const submitHandler = async (event) => {
    event.preventDefault()
    setUserData( {username, password})

    const response = await loginUser(username, password)
    alert({response})
    console.log(response.data)
    
  }

This API call returns from the loginUser function, when called by onSubmit:

{success: true, error: null, data: {…}}
data: {token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2M…TU2fQ.4l7g5y8hlEDxlmkWUPiVIfM6XWCqHa0410QXGLy72vw', message: 'Thanks for logging in to our service.'}
error: null
success: true
[[Prototype]]: Object

However, whatever I try to access the return data from the submitHandler (such as console.log or any variation of response.data.token I try, I just get null. As of right now the only way for me to access any API returns in my API folder are via local storage.

Please help me identify what i am missing.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First of all, you are using both promises (.then) and async await.

When you await the fetch.then.then you actually awaits for the last returned value. In your case, since you return nothing (undefined) from your last .then, you can't access the data.

Try return the result -

const response = await fetch(`${BASE}/users/login`, {...})
  .then(response => response.json())
  .then(result => {console.log(result)
     const key = result.data.token
     localStorage.setItem('stToken', JSON.stringify(key))
     localStorage.setItem('username', JSON.stringify(username))
     return result; // this is the line I added
   })
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