Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Initializing a custom Svelte store asynchronously

$
0
0

Background
I am attempting to develop a cross-platform desktop app using Svelte and Tauri
When the app starts i need to load a settings.json-file from the filesystem into a custom Svelte store.
It needs to be a custom store because I must validate the data using a custom set-function before writing to it
The store will hold an object.

I am using regular Svelte and not Svelte-kit as SSR is not necessary.

Problems

  1. Tauri does not have any synchronous methods for reading files in their fs-api
  2. Svelte does not seem to have any intuitive way I can find for doing this

Tests

  • Following Svelte's promiseStore example, this works for regular stores but not custom stores as the custom set method cannot be reached
  • Using a recursive timout-function waiting for the file to be read
  • Using a while-loop waiting for the file to be read
  • Attempted to find a way to load the data into a global variable before Svelte initializes

Example
It would be a lot of code if I were to post all the failed attempts, so I will provide a example of what I am attempting to achieve.
Everything in the code works when createStore is not async, except reading the settings-file.

import { writable, get as getStore } from 'svelte/store'; // Svelte storeimport _set from 'lodash.set';                            // Creating objects with any key/pathimport _merge from 'lodash.merge';                        // Merging objectsimport { fs } from '@tauri-apps/api';                     // Accessing local filesystemasync function createStore() {  // Read settings from the file system  let settings = {}  try { settings = JSON.parse(await fs.readTextFile('./settings.json')); }  catch {}  // Create the store  const store = writable(settings);  // Custom set function  function set (key, value) {    if(!key) return;    // Use lodash to create an object    const change = _set({}, key, value);    // Retreive the current store and merge it with the object above    const currentStore = getStore(store)    const updated = _merge({}, currentStore, change)    // Update the store    store.update(() => updated)    // Save the updated settings back to the filesystem    fs.writeFile({      contents: JSON.stringify(updated, null, 2),      path: './settings.json'}    )  }  // Bundle the custom store  const customStore = {    subscribe: store.subscribe,    set  }  return customStore;}export default createStore();

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>