Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching data from server in Remix.run

I was exploring Remix.run and making a sample app. I came across an issue that has been bothering me for some time now. Correct me if I am wrong: action() is for handling Form submission, and loader() is for fetching data initially. For my application, I used mongoose to connect MongoDB, defined models, and defined querying function in a query.server.ts file. I want to fetch data from the database through a function defined in the query.server.ts file when an image is clicked on the UI. How can I do that without using forms? I cannot pre-fetch the data without knowing what image was clicked by the user.

like image 371
canaryGrapher Avatar asked Jul 27 '26 03:07

canaryGrapher


1 Answers

You can create a resource route. These are like regular routes, but don't export a default component (no UI).

You can use the useFetcher hook and call fetcher.load() to call your resource route. The data is in fetcher.data.

// routes/query-data.ts
export const loader: LoaderFunction = async ({request}) => {
  const url = new URL(request.url)
  const img = url.searchParams.get('img')
  const data = await getData(img)
  return json(data)
}

// routes/route.tsx
export default function Route() {
  const fetcher = useFetcher()

  const handleImgClick = (e) => {
    const img = e.target
    fetcher.load(`/query-data?img=${img.attr('src')}`)
  }

  return (
    <div>
      <img onClick={handleImageClick} src="/images/file.jpg" />
      <pre>{ JSON.stringify(fetcher.data, null, 2) }</pre>
    </div>
  )
}
like image 113
Kiliman Avatar answered Jul 28 '26 15:07

Kiliman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!