简体   繁体   中英

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.

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>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM