Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!