sannajammeh / trpc-swr

tRPC-ified SWR hooks
https://trpc-swr.vercel.app
MIT License
209 stars 5 forks source link

re-fetching data with different input #37

Closed hasssanezzz closed 1 year ago

hasssanezzz commented 1 year ago

This is my first time opening an issue, thus, I don't know If this is considered an issue or not, but I am having trouble re-fetching data with different input on every fetch.

I read the documentation a lot of times trying to get the solution, But I couldn't.

Consider reading this block of code with focusing on the comment to understand my problem.


export default function ProductView() {
  const { data, error, isLoading, mutate } = trpc.products.list.useSWR({
    min: 200,
    max: 10000,
    brand: '',
    type: '',
  })

  // how can I re-fetch with different input??
  async function handleFilterSubmit(filter: FilterOptions) {
    // I want to change the input to this `filter` parameter, but I don't know how?
     await mutate()
  }

  return !isLoading ? (
    <Container className="flex items-start md:flex-row flex-col gap-5 my-10">
      <FilterBar
        products={data as Product[]}
        onSubmit={handleFilterSubmit}
      />

      ...

  ) : (
    <></>
  )
}

Please let me know if this is not considered an issue.

sannajammeh commented 1 year ago

Thanks for the issue! Vercel's SWR docs should clarify this a bit better imo.

SWR itself doesn't have support for this. My suggestion is moving the input into a state called filter and setting it on submit.

The hook will then automatically re-fetch with the new input.

Generally mutate is only used with existing inputs or no inputs.

State should control the rest like your hook updating above.