#SessionStorage is not defined inside a useTask$

3 messages · Page 1 of 1 (latest)

storm vale
#

Hi Everybody.

I would like to pass a sort parameter to an endpoint.
This sort parameter is managed by the user with a select.
So if the user change the sort parameter I would like to fetch again my data sorted in the right way.

I use useTask$ in order to track the changes in the sort parameter and call inside it the new fetch.
The fetch needs an auth token, stored in the SessionStorage, so everything works fine until I try to reload the page.

useTask$(async ({ track }) => {
    const abortController = new AbortController();
    track(() => sortParameter);
 
    const response = await fetch(
      {
        ...
        orderBy: sortParameter,
        ...
      },
      abortController
    );
  });

Every time I reload my window code throws the error "Session Storage is not defined".

I also tried to wrap the fetch inside an if statement in order to check if SessionStorage is defined and then do the API call, but again I received the same error: "Session Storage is not defined"

useTask$(async ({ track }) => {
    const abortController = new AbortController();
    track(() => sortParameter);
 
    if(sessionStorage) {
      const response = await fetch(
        {
          ...
          orderBy: sortParameter,
          ...
        },
        abortController
      );
    }
  });

If I understand well the useTask$ I think the reason of sessionStorage undefined is that this "hook" run also when the component is not rendered (so we don't have the sessionStorage). But I didn't find another way to track some parameter change and run an action after this change.

Anyone have some suggestions? Am I using the right "hook" for this kind of stuff?

Thanks

#

SessionStorage is not defined inside a useTask$

tardy sedge
#

You should be able to use if (isBrowser) inside of the useTrack for client side only code ✌🏼