Home > OS >  How to display an JSON object using axios and react query
How to display an JSON object using axios and react query

Time:10-29

here,s the screenshot of error

im newbie to REACT JS, kindly help me to sort out this problem

How to display json object in react using AXIOS and react-query hook. when i start the application it throws an error

Uncaught TypeError: data is undefined

home component is being imported in app.js file and wrapped with react-query hook

import './App.css';
import { Axios } from 'axios';
import {QueryClient,QueryClientProvider} from "@tanstack/react-query"
import {BrowserRouter as Router,Routes,Route} from "react-router-dom"
import { Home } from './pages/Home';
import { Profile } from './pages/Profile';
import { Contact } from './pages/Contact';
import { Navbar } from './Navbar';
//import { useState,createContext } from 'react';

function App() {
const client  = new QueryClient();

return (
\<div className="App"\>
\<QueryClientProvider client={client}\>
\<Router\>
\<Navbar /\>

        <Routes>
          <Route path="/" element={<Home  />} />
          <Route path="/profile" element={<Profile  />} />
          <Route path="/contact" element={<Contact />} />
          <Route path='*' element = {<h1>page not found</h1>} />
    
        </Routes>
      </Router>
      </QueryClientProvider>
      
     
    </div> 

);
}

export default App;

i have created a home component, in which json object is fetched by using use query and axios

import {useQuery} from "@tanstack/react-query";
import { Axios } from "axios";

export const Home = () =\> {
const { data } = useQuery(\["catfact"\],() =\> {
return Axios.get("https://catfact.ninja/fact").then((res) =\> res.data)
})
return(

    <h1>
        {""}
         this is the homepage<p>{data.fact}</p>
    </h1>

)}

github link

api link: https://catfact.ninja/fact

CodePudding user response:

I didn't use useQuery as I have no knowledge about it, but is how you'd show the data using axios:

import axios from "axios";
import { useEffect, useState } from "react";
export default function App() {
  const [apiData, setApiData] = useState([]);

  useEffect(() => {
    axios.get("https://catfact.ninja/fact").then((res) => setApiData(res.data));
  }, []);

  console.log(apiData);
  return <div className="App">{apiData?.fact}</div>;
}

And the code link: https://codesandbox.io/s/naughty-leavitt-mwcj5k?file=/src/App.js

  • Related