sveltesveltekitsvelte-component

Conditional Rendering of Contents of Navbar


I am trying to conditionally render different parts of my navbar to the user depending on if they are logged in or not. I initially achieved this by using the onMount function, but it is not ideal as there is a slight delay after the page loads before the right navbar contents are shown. I could fix this by adding a loading indicator, but I don't want to do that.

So, I want to get the response from the server and then render out the right navbar to the user as soon as the page loads. I used the load function in my +layout.js as shown below -

export async function load({ fetch }) {
    try {
        console.log('Fetching admin status from API...');

        const response = await fetch('http://localhost:8000/check-admin-status/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
        });

        console.log('Response Status:', response.status); // Log the response status
        const data = await response.json();

        console.log('Fetched Data:', data); // Log the fetched data

        return {
            isAdmin: data.is_admin,
            isAuthenticated: data.is_authenticated,
        };
    } catch (error) {
        console.error('Error fetching admin status:', error);
        return {
            isAdmin: false,
            isAuthenticated: false,
        };
    }
}

This successfully returns the server's response -

Fetching admin status from API...
+layout.js:13 Response Status: 200
+layout.js:16 Fetched Data: {{is_admin: false, is_authenticated: true}
is_admin
: 
false
is_authenticated
: 
true

But how do I inform my Navbar of this response?

in my +page.svelte, which is in the same directory as my +layout.js I have -

<script>
  import Navbar from "../components/Navbar.svelte";
  import Modal from "../components/Modal.svelte";

  export let isAdmin;
  export let isAuthenticated;

  // Log the props to verify they are received correctly
  console.log('Page Props - isAdmin:', isAdmin);
  console.log('Page Props - isAuthenticated:', isAuthenticated);
</script>

<Navbar {isAdmin} {isAuthenticated}/>

<Modal modalId="exampleModal" modalTitle="Create an account to like or comment." />

But the log statements come out as undefined

What I want to do is get the server's response in my +layout.js (which I have successfully gotten) > pass it to the +page.svelte, and then further pass it on to my Navbar component so that the appropriate parts of the Navbar would be rendered to the user as the page loads.

my folder structure is -

src > routes > +page.svelte and +layout.js

it is my homepage

this is my Navbar.svelte -

<script>
export let isAdmin;
export let isAuthenticated;
</script>

<!-- preceding html -->
      <ul class="navbar-nav ms-auto d-flex align-items-center">
        {#if isAdmin}
          <li class="nav-item">
            <a class="nav-link d-flex align-items-center me-3" href="#" data-bs-toggle="modal" data-bs-target="#exampleModal">
              <i class="bi bi-pencil-square"></i> Write
            </a>
          </li>
        {/if}
        {#if isAuthenticated}
          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="bi bi-bell"></i> 
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/profile">
              <i class="bi bi-person-circle profile-icon"></i>
            </a>
          </li>
        {:else}
          <li class="nav-item">
            <button class="btn sign-up me-3" data-bs-toggle="modal" data-bs-target="#exampleModal">Sign up</button>
          </li>
          <li class="nav-item">
            <a class="nav-link me-3" href="/signin">Sign in</a>
          </li>
        {/if}
      </ul>

What to do?


Solution

  • Pages and layout do not accept arbitrary properties, all data from load functions is passed to a property called data. So the values will be on data.isAdmin & data.isAuthenticated.

    See the data loading docs.

    You also do not have to pass load data down, you can access it via the page store, so in Navbar you can just use $page.data.isAdmin directly.