7

I'm learning remix and I'd have some functions in my loader that I call in my default route with useLoaderData like so :

export const loader = async () => {
  const pokemon = await getRandomPokemon();
  const types = await getAllPokemonTypes();
  return [pokemon, types.results];
};

export default function App() {
  const [pokemon, types] = useLoaderData();
...
}

I'd like to add a button to reload data (since I want a new random pokemon in this case) everytime I click on it

André Werlang
  • 5,839
  • 1
  • 35
  • 49
Jimmy Soussan
  • 652
  • 3
  • 14

2 Answers2

12

There is another way to update the data, but without using Form component:

import { useRevalidator } from 'react-router-dom';

...

export default function App() {
  const [pokemon, types] = useLoaderData();
  const revalidator = useRevalidator();

  // run when you need to update
  revalidator.revalidate()
}

More info you can find in the official documentation.

Roman Meyer
  • 2,634
  • 2
  • 20
  • 27
  • 1
    Thank you so much, I'm working with `react-router-v6` right now and I was looking for a way to refetch the `loader()` function, works for that as well! – Thimma Jan 09 '23 at 09:39
  • I had to import it as `import { useRevalidator } from "@remix-run/react";`. This also required me to bump my version (I was at 1.8 and I went to 1.11.1) https://remix.run/docs/en/v1/hooks/use-revalidator#userevalidator – dmc85 Jan 22 '23 at 20:04
8

Use a remix Form (or HTML form):

<Form method="get">
  <button type="submit">Reload</button>
</Form> 

Submitting this form will execute the loader function.

Komo
  • 2,043
  • 1
  • 22
  • 35