How to update fetch and useLoaderData() using react-router
P粉883223328
P粉883223328 2023-08-26 12:39:34
0
1
449
<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>
P粉883223328
P粉883223328

reply all(1)
P粉373990857

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:

const router = createBrowserRouter([
  {
    index: true,
    element: <CountriesList />,
    loader: countriesLoader,
    action: findCountry
  }
]);

<RouterProvider router={router} />
const countriesLoader = async () => {
  const res = await fetch("https://restcountries.com/v3.1/all/");
  if (!res.ok) {
    throw Error("无法获取数据!");
  }
  return res.json();
};
const findCountry = async ({ request }) => {
  const formData = await request.formData();

  const res = await fetch(
    `https://restcountries.com/v3.1/name/${formData.get("country")}`
  );
  if (!res.ok) {
    throw Error("无法获取数据!");
  }
  return res.json();
};
import {
  Form,
  useActionData,
  useLoaderData
} from "react-router-dom";

const CountriesList = () => {
  const searchResult = useActionData();
  const countriesData = useLoaderData();

  return (
    <>
      ...

      <Form method="post" replace>
        <label>
          搜索 <input required type="text" name="country" />
        </label>
        <button type="submit">创建</button>
      </Form>

      ...
    </>
  );
};

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!