How to update fetch and useLoaderData() using react-router
P粉883223328
2023-08-26 12:39:34
<p>I want to update the data of useLoaderData() after submitting the form.
In my case: </p>
<pre class="brush:php;toolbar:false;">export const countriesLoader = async () => {
const res = await fetch("https://restcountries.com/v3.1/all/");
if (!res.ok) {
throw Error("Unable to access data!");
}
return res.json();
};</pre>
<p><code><Route index element={<CoutriesList />} loader={countriesLoader} /></code></p>
<p>In the CountriesList element: </p>
<p><code>const country= useLoaderData();</code></p>
<p>I want to update countries with new data in useLoaderData(): </p>
<pre class="brush:php;toolbar:false;">const findCountry = async () => {
const res = await fetch(
`https://restcountries.com/v3.1/name/${searchText}`
);
const data = res.json();
return data;
};</pre>
<p>So when I submit, I want the data of countriesLoader to become the data of findCountry. </p>
<p>Is there any solution? Thank you</p>
I think you might want to use
findCountry
as the routing action when submitting the form. The loader is run the first time a route is loaded. An action can be scheduled later.Basic example: