How can I fetch additional data after the page is already rendered with remix?

99 Views Asked by At

I'm using a loader to fetch the ids of several resources and the user can select the ids of the ones they would like to load.

I haven't found a way to pass new arguments to the loader to GET new data after the page is loaded.

Created a Stack Overflow account specifically because of this. Would super appreciate any help!!

I've found that remix loaders can only accept request, params, and context.

One possible solution may be passing params through the URL but I'm hoping to find a different solution because I need to be able to pass an array of ids. I also haven't gotten this solution to work.

Another solution I explored is appending the ids with formState but that wouldn't reload the page (so the loader wouldn't make another request with the new params).

1

There are 1 best solutions below

0
Kiliman On

With Remix, you can use fetchers (useFetcher). It supports JSON payloads as well as FormData. Since you want to send a payload (your array data) in the body, you'll want to use the POST method which means you'll need to create an action function.

// routes/test.tsx

// actions are for handling POST requests instead of GET (loaders)
export async function action({ request }: ActionFunctionArgs) {
  // get JSON payload
  const { ids } = await request.json()
  
  // process data

  // return a JSON response
  return json({ success: true })
}

export default function Component() {
  const fetcher = useFetcher<typeof action>()

  const handleClick = () => {
    const ids = [1, 2, 3]
    
    // POST JSON payload
    fetcher.submit({ ids }, {
      method: "POST",
      encType: "application/json",
    }) 
  }

  return (
    <div>
      <button onClick={handleClick}>Click Me</button>
      <pre>{JSON.stringify(fetcher.data, null, 2)}</pre>
    </div>
  )
}

https://remix.run/docs/en/main/hooks/use-fetcher