Home  >  Q&A  >  body text

How to update fetch and useLoaderData() using react-router

<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粉883223328P粉883223328392 days ago418

reply all(1)I'll reply

  • P粉373990857

    P粉3739908572023-08-27 11:27:14

    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>
    
          ...
        </>
      );
    };

    reply
    0
  • Cancelreply