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

96
Views
What can I do so object.property doesn't return undefined?

I'm trying to create a function that first fetches the JWT access tokens from my current session and then applies that to the Authorization header of my actual request. This works fine, but the end result is that I want to return the full response object.

I've tried assigning some of the output to a output object, but when I try to console.log some of the properties, then it just returns undefined. If I do console.log inside the browser, then I can see the output but I can never print the actual properties.

export default function fetcher(url, method, body = null) {
  const output = {}
  fetch("/api/auth/session")
    .then((response) => {
      return response.json()
    })
    .then((data) => {
      const token = data.user.accessToken
      if (method.toLowerCase() == "post") {
        const res = fetch(url, {
          method: "post",
          headers: {
            Authorization: "Bearer " + token,
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
          },
          body: body,
        }).then((response) => {
          Object.assign(output, {
            status: response.status,
          })
        })
      } else {
        const res = fetch(url, {
          method: "get",
          headers: {
            Authorization: "Bearer " + token,
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
          },
        })
          .then((response) => response.json())

          .then((data) => {
            Object.assign(output, data)
          })
      }
    })
    .catch((err) => {
      // Do something for an error here
    })
  console.log(output)
  console.log(output.status)

  return output
}

Console.logs

End goal is to call the function from some other file like this

const test = fetcher("http://api.localhost/v1/projects", "post", JSON.stringify({ name: event.target.name.value }))

console.log(test.status)
about 4 years ago · Juan Pablo Isaza
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!