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
You can created customized hook to call the API and use that returned result ( API result ) in any react component.
The
<Outlet>
is also a context provider. You can pass values via thecontext
property (see type decleration), and then retrieve them withuseOutletContext()
:And remove the prop
api
in your routes:Call
useOutletContext
in the components that actually use theapi
key.