Home > other >  Fetching data from server in Remix.run
Fetching data from server in Remix.run

Time:06-12

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.

CodePudding user response:

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 fetch = 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>
  )
}
  • Related