skip to Main Content

I am trying to build an e-commerce demo site with Next.js 13 using the app directory and tRPC.

I already made most of the admin dashboard and pretty much all of the core site functionality (cart, ordering, payments with stripe, order management on the admin dashboard, adding new products, adding new product types, different store configurations etc.). The user can view the live data on the admin dashboard (eg. after they make an order they can log in with an demo admin account and view their live data) but they can’t make direct changes to the database, like adding / modifying a product or changing the store configurations.

This is where the problem arises, I want to let the user toggle a button on the dashboard and instead of showing them the live data taken from the database show them local data they saved in their localStorage. Is there any way I can intercept a request in tRPC so I can return the data saved in the user’s localStorage instead of the live database data?

I was thinking something like this

const { data } = api['...'].useQuery(undefined /* no input */, {

    onSuccess: (data) => {

        if (data.useLocalStorage) return localStorage.get("Item");

        return data;
    }

})

Is there any way to do this with tRPC? If no is there any alternative I can use to achieve this functionality?

2

Answers


  1. trpc is using useQuery under the hood, we can utilize the enabled property to pause / enable the data fetching.

    For this you could create a custom hook which controls the logic of getting local / live data for you

    const myCustomHook = () => {
      const [showLocalData, setShowLocalData] = useState(false)
    
      const { data } = api['...'].useQuery(undefined /* no input */, {
        enabled: showLocalData
      })
    
      const localData = useMemo(() => {
         return localStorage.get("Item");
      }, [showLocalData])
    
      return {
        data: showLocalData ? localData : data,
        showLocalData, // use to set toggle value
        setShowLocalData // use to toggle between live & local data
      }
    }
    
    const MyComponent = () => {
     const { data } = myCustomHook()
    
     // ... your component
    }
    
    Login or Signup to reply.
  2. https://trpc.io/docs/reactjs/usequeries

    you can use useQueries to do something like this

      // let's assume you have { name: 'john doe', age: 18 } with key `profile` saved in local storage
      const localItem = localStorage.getItem('profile');
    
      const [result] = trpc.useQueries((t) => [
        localItem ? {
          queryKey: ['localStorageQuery'],
          queryFn: () => localItem,
        } : t.getItemFromServer(),
      ])
    
      // will print john doe in console 
      console.log(result.data.name)
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search