Skip to content
Source
Sign inSign up
TanStack/store

Undefined Value from store subscribe #49

Closedajayarulraj(GitHub profile, opens in a new tab) opened this issue 1 comment

Describe the bug

Hello, I am trying to use subscribe event for persist the store data in local storage. Looks like the value which is coming from subscribe event is undefined.

can anyone please let me know if any issues here ?

Steps to Reproduce the Bug or Issue

import { useEffect, useState } from "react";
import { Store, useStore } from "@tanstack/react-store";

const initialState = { count: 0 };

const counterStore = new Store(initialState);

function App() {
  const counter = useStore(counterStore, (state) => state.count);

  const increment = () =>
    counterStore.setState((state) => {
      return {
        ...state,
        count: counter + 1,
      };
    });

  const decrement = () =>
    counterStore.setState((state) => {
      return {
        ...state,
        count: counter - 1,
      };
    });

  useEffect(() => {
    const unsubscribe = counterStore.subscribe((value) => {
      console.log(value); // value is undefined
      localStorage.setItem("counter", JSON.stringify(value.count));
    });

    return () => unsubscribe();
  }, [counterStore]);

  return (
    <>
      <p>Count: {counter}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </>
  );
}

export default App;

Expected behavior

useEffect(() => {
    const unsubscribe = counterStore.subscribe((value) => {
      console.log(value); // value is undefined
      localStorage.setItem("counter", JSON.stringify(value.count));
    });

    return () => unsubscribe();
  }, [counterStore]);

Screenshots or Videos

No response

Platform

  • OS: [e.g. macOS, Windows, Linux]
  • Browser: [e.g. Chrome, Safari, Firefox]
  • Version: [e.g. 91.1]

Additional context

No response

  1. .subscribe doesn't provide you the value of the store, you'll need to read store.state in the subscribe instead

Sign in to join this conversation.