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

120
Vistas
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 Respuestas
Responde la pregunta

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