Skip to content

Commit bebf08c

Browse files
Update examples.md (#1419)
add example of using getter for dynamic header
1 parent 06c04a0 commit bebf08c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/src/content/docs/openapi-fetch/examples.md

+31
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,37 @@ client.GET("/some-authenticated-url", {
7272
});
7373
```
7474

75+
### Vanilla JS getter
76+
77+
You can also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get" target="_blank" rel="noopener noreferrer">getter</a>:
78+
79+
```ts
80+
// src/lib/api/index.ts
81+
import createClient from "openapi-fetch";
82+
import { paths } from "./v1";
83+
84+
let authToken: string | undefined = undefined;
85+
someAuthMethod().then((newToken) => (authToken = newToken));
86+
87+
export default createClient<paths>({
88+
baseUrl: "https://myapi.dev/v1/",
89+
headers: {
90+
get Authorization() {
91+
return authToken ? `Bearer ${authToken}` : undefined
92+
}
93+
}
94+
});
95+
```
96+
97+
```ts
98+
// src/some-other-file.ts
99+
import client from "./lib/api";
100+
101+
client.GET("/some-authenticated-url", {
102+
/**/
103+
});
104+
```
105+
75106
## Frameworks
76107

77108
openapi-fetch is simple vanilla JS that can be used in any project. But sometimes the implementation in a framework may come with some prior art that helps you get the most out of your usage.

0 commit comments

Comments
 (0)