javascriptreactjsmantine

when get value from useSessionStorage Mantine Hook always return default value at first time


i save filter value to session storage, but when i open the page again, the filter value from session storage not return a actual value but return default value from hook. i create session storage like this

  const [zoneFilterSaved, setZoneFilterSaved, removeZoneFilter] = useSessionStorage({
    key: 'activity_v2_zone_filter',
    defaultValue: ZONE_FILTER_INITIAL_VALUES,
    serialize: superjson.stringify,
    deserialize: (str) => (str === undefined ? null : superjson.parse(str)),
    getInitialValueInEffect: true,
  });

how to get actual filter value from session storage at first time when open page


Solution

  • The issue you're facing may be related to the getInitialValueInEffect option set to true in your useSessionStorage hook. When getInitialValueInEffect is set to true, it retrieves the initial value from session storage within a useEffect. This can lead to the initial value being set to the default value when the component first mounts.

    To ensure that you get the actual filter value from session storage when you open the page for the first time, you can modify your code as follows:

    import useSessionStorage from 'use-sessionstorage'; // Import your library
    
    const ZONE_FILTER_INITIAL_VALUES = {
      // Your initial filter values here
    };
    
    function YourComponent() {
      // Don't use getInitialValueInEffect, which is causing the issue
      const [zoneFilterSaved, setZoneFilterSaved, removeZoneFilter] = useSessionStorage({
        key: 'activity_v2_zone_filter',
        defaultValue: ZONE_FILTER_INITIAL_VALUES,
        serialize: superjson.stringify,
        deserialize: (str) => (str === undefined ? null : superjson.parse(str)),
      });
    
      // ...
    
      return (
        // Your component JSX
      );
    }
    
    export default YourComponent;

    By removing getInitialValueInEffect, the zoneFilterSaved variable should correctly retrieve the value from session storage without being affected by the default value when the component first mounts. This change should ensure that you get the actual filter value from session storage when you open the page for the first time.