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

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