0

I am small working on a small Tauri app. For the state management. am using Redux Toolkit.

Until now i have been using localStorage to persist my data but i would like to change to something that allows me to save more data, like a JSON file on the app's data folder.

To do that i am rewritting my middleware "save function" and my "rehydrate" function to use Tauri's fs and path API.

Saving the data works ok. For that i am using a custom middleware, which saves the data on the $APPLOCALDATA directory as a JSON file (in the configureStore middleware).

What i now would like to do is to read that data when the app loads and set it as the preloadedState on the store (inside the configureStore function).

My problem is that Tauri exposes an async readTextFile function, but the configureStore preloadedState cannot be a call to a async function.

Any idea how i can do this?

This is the code i have store.ts

export const store = configureStore({
    reducer: {
        ...my reducers are here...
    },
    preloadedState: reHydrateStore(),
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(localStorageMiddleware)
});

the reHydrateStore function

export const reHydrateStore = (): any => {
    console.log('NEED TO HYDRATE STORE');

    if (localStorage.getItem(APP_NAME) !== null) {
        // @ts-expect-error
        return JSON.parse(localStorage.getItem(APP_NAME)); // re-hydrate the store
    }
};

I would like to change getting the data from localStorage, to getting it from the file.

Any help would be much appreciated.

If there are any other better ways to save the data, i am also open to suggestions!

Thank you!

Boguz
  • 1,600
  • 1
  • 12
  • 25

1 Answers1

0

I'm actually searching for similar solution. What I've found so far...

You should use @tauri-apps/api/fs for this.

Read file

import { readTextFile, BaseDirectory } from '@tauri-apps/api/fs';
// Read the text file in the `$APPCONFIG/app.conf` path
 const contents = await readTextFile('app.conf', { 
 dir:BaseDirectory.AppConfig });

Write file

import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';
// Write a text file to the `$APPCONFIG/app.conf` path
await writeTextFile('app.conf', 'file contents', { dir: 
BaseDirectory.AppConfig });

Here some video reference

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 15 '23 at 11:19