Home > database >  Type Error after adding localstorage to store
Type Error after adding localstorage to store

Time:11-18

On the initial page load I get a Type Error:

500
$rating.join is not a function
TypeError: $rating.join is not a function

This stops after a page change, for example, going to the about page and then back to the index page it will load properly.

I'm thinking it's an order of operations problem? Fixed by onMount? Just not sure how to implement it.

// Store
export const rating = writable(browser && (JSON.parse(sessionStorage.getItem("rating")) || []))
rating.subscribe((val) => browser && sessionStorage.setItem("rating", JSON.stringify(val)))

// Filters Component
<script>
  import {rating} from "../stores/items";
  const ratings = [1, 2, 3, 4, 5];
</script>

  <div class="flex justify-center">
    <!-- Ratings Filter -->
    <div class="multiselect">
      <div class="selectBox rounded-sm shadow2 m-1 px-1" on:click={multiselect}>
        <select>
          <option
            >{#if $rating.length === 0}
              Rating:
            {:else}
              {$rating.join(", ")}
            {/if}</option
          >
        </select>
      <div class="overSelect dropdown" />
    </div>
    <div class="checkboxes" id="ratingDropdown">
      {#each ratings as ratings}
      <div class="flex">
        <input
          type="checkbox"
          id={ratings}
          name="typeValues"
          bind:group={$rating}
          value={ratings}
          class="dropdown"
        />
        <label for={ratings} class="dropdown">{ratings}</label>
      </div>
      {/each}
    </div>
  </div>

Any help would be appreciated, thanks.

CodePudding user response:

I think your brackets are wrong in the initial call

const rating = writable(
   browser && 
   (JSON.parse(sessionStorage.getItem("rating")) || [])
)

This would mean that during SSR rating will be false

You probably want to shift them around:

const rating = writable(
   (browser && JSON.parse(sessionStorage.getItem("rating"))) || 
   []
)

This way when browser is false, you will get an emptry array.

(The awkward formatting is to try making it visible what happens)

CodePudding user response:

console.log ($rating) and see what you get.

  • Related