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