skip to Main Content

I was working on a project that fetches data from swiggy api, but now I have added routing to the project. I don’t know how can I use a state variable outside of the component but in the same file.

I’m trying to access the api in element : <BodyLayout api={api} />.

const App = () => {
  const [api, setAPI_KEY] = useState(PUNE_API);

  const handleAPIKeyChange = (newAPIKey) => {
    console.log("API Key changed to:", newAPIKey);

    setAPI_KEY(newAPIKey);
  };

  return (
    <div className="app">
      <Header onAPIKeyChange={handleAPIKeyChange} />
      <Outlet/>
      
      <Footer />
    </div>
  ); 
};

const appRoute = createBrowserRouter([
  {
      path : "/",
      element : <App/>,
      errorElement : <RouterError/>,
      children:[
        {
          path : "/home",
          element : <BodyLayout api={api} />,
          
      },
        {
          path : "/",
           element : <BodyLayout api={api} />,
         
      },
        {
          path : "/about",
          element : <About/>,
      },
      {
        path : "/contact",
        element : <Contact/>,
       
      },
      {
        path : "/cart",
        element : <Cart/>,
       
      },
      {
        path : "/offers",
        element : <Offers/>,
       
      },
      ],
  },
]);
 
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<RouterProvider router={appRoute}/>);

I have tried multiple way but not worked.

2

Answers


  1. You can created customized hook to call the API and use that returned result ( API result ) in any react component.

    Login or Signup to reply.
  2. The <Outlet> is also a context provider. You can pass values via the context property (see type decleration), and then retrieve them with useOutletContext():

    const App = () => {
      const [api, setAPI_KEY] = useState(PUNE_API);
    
      const handleAPIKeyChange = (newAPIKey) => {
        setAPI_KEY(newAPIKey);
      };
    
      return (
        <div className="app">
          <Header onAPIKeyChange={handleAPIKeyChange} />
          
          <Outlet context={api} />
          
          <Footer />
        </div>        
      );
    };
    

    And remove the prop api in your routes:

    {
      path : "/home",
      element : <BodyLayout />,        
    },
    

    Call useOutletContext in the components that actually use the api key.

    const SampleComponent = () => {
      const api = useOutletContext();
    
      //...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search