Jimmy Soussan
Jimmy Soussan

Reputation: 722

Is there a way to refetch with useLoaderData in remix?

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

Upvotes: 9

Views: 12216

Answers (2)

Roman Meyer
Roman Meyer

Reputation: 2872

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.

Upvotes: 19

Komo
Komo

Reputation: 2138

Use a remix Form (or HTML form):

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

Submitting this form will execute the loader function.

Upvotes: 9

Related Questions