I am very new when it comes to using react hooks, rendering, and routing.
App.js
function App() {
return (
<div className="App">
<Navbar />
</div>
);
}
Navbar.js
export default function Navbar() {
return(
<BrowserRouter>
<Routes>
<Route path = '/:page' element = {<Header/>} />
<Route path='/' element={<Header/>} />
<Route exact path='' element = {<Home/>}/>
<Route exact path='home' element = {<Home/>}/>
<Route exact path='players' element = {<BasicTable/>}/>
<Route exact path='about' element = {<About/>}/>
<Route path="*" element={<Home />} />
</Routes>
</BrowserRouter>
)
}
BasicTable.js
const getObj = async () => {
const value = await axios.get(...);
return value;
}
export function BasicTable(){
const [obj, setObj] = useState();
console.log("getting object");
useEffect (()=> {
console.log("using Effect");
setObj(getObj());
}, []);
//Rest of the code below this...
}
I am trying to get the axios get call to trigger everytime someone navigates to the basic table page (/players page). If I just insert the axios.get call naked into the basic table function, this causes an infinite loop of api get calls. Now I am using the useEffect hook, but it never triggers when I navigate to "/players". In fact, it never triggers. The only thing I see is the "getting objects" console log, but never "using Effect". Am I missing an important part of useEffect?
The useEffect hook is updating the obj state to the implicitly returned Promise object with setObj(getObj());. At a minimum, the useEffect hook needs to wait for the getObj function to resolve. This can be done in a couple of ways:
const getObj = async () => {
const value = await axios.get(...);
return value;
}
Using async/await:
export function BasicTable(){
const [obj, setObj] = useState();
console.log("getting object");
useEffect (()=> {
console.log("using Effect");
const getObject = async () => {
const obj = await getObj();
setObj(obj);
}
getObject();
}, []);
// Rest of the code below this...
}
Using Promise chain:
export function BasicTable(){
const [obj, setObj] = useState();
console.log("getting object");
useEffect (()=> {
console.log("using Effect");
getObj().then(obj => setObj(obj));
}, []);
// Rest of the code below this...
}
In fact, because getObj implicitly returns a Promise object, you can simply return the Promise from axios.
const getObj = () => {
return axios.get(...);
}