I am trying to fetch an api using axios and set it in a state in my App.js file
import React, { useEffect, useState } from "react";
import "./App.css";
import axios from "axios";
import UserDetails from "./user/userDetails";
function App() {
useEffect(() => {}, []);
const [userDetails, setUserDetails] = useState([]);
const getUser = async () => {
try {
return await
axios.get("https://randomuser.me/api").then((response) => {
if (response.data.results) {
setUserDetails(response.data.results);
}
});
} catch (error) {}
};
getUser();
console.log("!!!!!!!!!!!!!!!!!", userDetails);
return <>{<UserDetails data={userDetails} />}</>;
}
export default App;
i am able to get the response from getUser function but was not able to set in in userDetails what is wrong in this implementation
3
Answers
call the getUser function inside useEffect
you can try to call this function getUser(); in the use effect that time is working
Moved the
getUser
function inside theuseEffect
hook and called it usingfetchUserDetails
function. Also updated thesetUserDetails
function with the actual data from the response.