3

I am trying to persist data to AsyncStorage using Zustand.

Here is my code for the store:

//store.ts

export const useAuthStore = create(
  persist(
    (set) => ({
      token: "",
      setToken: (token) =>
        set((state) => ({
          token: token,
        })),
    }),
    {
      name: "token",
      getStorage: () => AsyncStorage,
    }
  )
);

Here is the code for my login page:

//login.tsx

  const setStoreToken = useAuthStore((state) => state.setToken);

  async function handleLogin() {
    setStoreToken("6747rt345t67324xn487r364qxuhfu");
    const storedToken = await AsyncStorage.getItem("token");
    console.log(storedToken);
  }

The console.log in login.tsx is here: {"state":{"token":"6747rt345t67324xn487r364qxuhfu"},"version":0}.

What I would like to get is "6747rt345t67324xn487r364qxuhfu", which is just the token without the session and version.

herbie
  • 335
  • 2
  • 14
  • can you please explain more..?, you need to compare the token of the store and async storage is it right or wrong..? – Ankit Vora Dec 28 '22 at 07:38
  • Hi @AnkitVora, the token is correct, The issue is the extra data (state and version} that I don't want to be stored. I am trying to get rid of these extra items so it just leaves me with the token only. – herbie Dec 28 '22 at 08:24
  • can you please share the code where you are storing the token. – Ankit Vora Dec 28 '22 at 08:55
  • Thats the code under ```//store.ts```. The persist middleware stores it in AsyncStorage. Here: ```{ name: "token", getStorage: () => AsyncStorage, }``` – herbie Dec 28 '22 at 09:06
  • 1
    can you please share this log ==> ```set((state) => ({ console.log(">>>",state) token: token, })),``` – Ankit Vora Dec 28 '22 at 09:13

1 Answers1

3

Using getStorage got deprecated in the latest version of Zustand, now it must be written like the following:

//store.ts
import { persist, createJSONStorage } from 'zustand/middleware';


export const useAuthStore = create(
  persist(
    (set) => ({
      token: "",
      setToken: (token) =>
        set((state) => ({
          token: token,
        })),
    }),
    {
      name: "token",
      storage: createJSONStorage(() => AsyncStorage), // <==  pay attention
    }
  )
);
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
  • I tried this. But the value of Token gets resolved to empty string everytime the app is starte so i don't think the async storage is working properly – tahaf10 Jun 08 '23 at 11:29