Skip to content

How to call an API with the idToken? #155

@JustinGuese

Description

@JustinGuese

Hi, I can't get my code to work, maybe someone can give me some help?

What I want to do is call an API with the idToken/Bearer of the user... I can get the Bearer inside of the <SignedIn let:user> component, but not in the <script> section... What am I doing wrong?

working example

My app, auth, etc are stored in '$lib/firebase', it's 1:1 as in the example

<script lang="ts">
    import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
    import { FirebaseApp, SignedIn, SignedOut } from 'sveltefire';
    import {  projects, crnt_project } from '$lib/docdata'; // simple writable

    async function loadProjects(bearertoken) {
        console.log("loading projects now form api")
        const response = await fetch('http://localhost:8001/projects', {
            method: 'GET',
            headers: {"accept" : "application/json", "Authorization": "Bearer " + bearertoken}
        });
        const json = await response.json();
        console.log("json response for projects: " + json)
        projects.set(json);
        return json;
    }

    let dataPromise;
</script>

<FirebaseApp {auth}>
    <SignedIn let:user let:signOut>
        This is the only way how I got it to work:
         {dataPromise = loadData(user.accessToken)}

         {#await dataPromise}
                <p>loading projects...</p>
          {:then projects}
               <form>
                       <select bind:value={$crnt_project} class="form-control" name="project" id="project">
                                            {#each projects as project} // would be nice btw to use $projects, but it's not set at this point ??
                                                {#if $crnt_project === project.id}
                                                    <option value={project.id}  selected>{project.name}</option>
                                                {:else}
                                                    <option value={project.id}>{project.name}</option>
                                                {/if}
                                             {/each}
                        </select>
                </form>
          {/await}
    </SignedIn>
</FirebaseApp>

what would I expect to be able to do?

<script>
    onMount() -> load all the data for the user with his bearerToken
</script>

{#await all data }
   please wait a moment...
{:then }
   render all the stuff
{/await}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions