I have a Context API file setup which has a state and a function which fetches data from an API and sets the state, and i want to pass the state down to my other components. In my App.js, I am using React-Router to specify the routes. How do i pass the state down to these components using Context API, whilst using React-Router.
My ApiContext.js file looks like this :
import React, {useState, createContext } from 'react';
export const ApiContext = createContext();
export const ApiProvider = async (props) => {
const [data, setData] = useState(null);
const getURL = 'https://examplefetchsite.com';
const response = await fetch(getURL).json();
setData(response);
return (
<ApiContext.Provider value={[data, setData]}>
{props.children}
</ApiContext.Provider>
);
}
My App.js's return looks like this :
return (
<ApiProvider>
<Router>
<div>
<NavBar />
<Switch>
<Route path="/" exact component={ Dashboard } />
<Route path="/create" component={ Create } />
<Route path="/view" component={View} />
</Switch>
</div>
</Router>
</ApiProvider>
)