I am a beginner at using ReactJS and currently following a video that uses React Query for fetching data from an API. This is the video I am following: https://www.youtube.com/watch?v=SYXvHXOJzwc&list=PLpPqplz6dKxW5ZfERUPoYTtNUNvrEebAR&index=10
I am particularly having errors on the code shown in timestamp 13:01. Here are my React components’ source code:
Home.js
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import Axios from 'axios';
export const Home = () => {
const { data } = useQuery(["cat"], () => {
return Axios.get("https://catfact.ninja/fact").then((res) => res.data);
});
return (
<div>
<h1>This is Home page </h1>
<p>{ data.fact }</p>
</div>
);
}
App.js
import './App.css';
import React from 'react';
import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom';
import { Home } from './Home';
import { Contact } from './Contact';
import { Profile } from './Profile';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
function App() {
const client = new QueryClient();
return (
<div className="App">
<QueryClientProvider client={ client }>
<Router>
<div>
<Link to="/">Home</Link>
<Link to="/profile" style={{margin : 10}}>Profile</Link>
<Link to="/contact" style={{margin : 10}}>Contact</Link>
</div>
<Routes>
<Route path="/" element={ <Home/> }></Route>
<Route path="/profile" element={ <Profile/> }></Route>
<Route path="/contact" element={ <Contact/> }></Route>
</Routes>
</Router>
</QueryClientProvider>
</div>
);
}
export default App;
This is my console log for further information:
I think I am currently having problems in line 6 of Home.js wherein I am trying to fetch the API data using Axios but I have no clue what the reason is. If anyone also followed this tutorial or encountered the same problem, may I ask how you fixed it? Thank you.
2
Answers
When you delete
does the page open?
If it opens, have you installed axios and react-query?
If it doesn’t open, are your routes and elements correct?
data
is going be undefined until the 1st request has succeeded, that’s expected behaviour.Use
isPending
(orisLoading
on versions before React Query 5) to check if data is loaded before displaying it: