skip to Main Content

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


  1. call the getUser function inside useEffect

    import React,{useEffect,useState} from 'react'
    import './App.css';
    import axios from "axios";
    import UserDetails from './user/userDetails';
    
    function App() {
    
     const [userDetails,setUserDetails]=useState([])
    
     useEffect(() => {
      getUser();
     },[])
    
     const getUser=async()=>{
      try {
       return await axios.get('https://randomuser.me/api').then(response => {
        if(response.data.results){
         setUserDetails(response.data.results);
        }
       });
      } catch (error) {
        console.log('ERROR',error);
      }
     }
    
     return <UserDetails data={userDetails}/>
    }
    
    export default App;
    
    Login or Signup to reply.
  2. you can try to call this function getUser(); in the use effect that time is working

    Login or Signup to reply.
  3. Moved the getUser function inside the useEffect hook and called it using fetchUserDetails function. Also updated the setUserDetails function with the actual data from the response.

    import React, { useEffect, useState } from 'react';
    import './App.css';
    import axios from 'axios';
    import UserDetails from './user/userDetails';
    
    function App() {
      const [userDetails, setUserDetails] = useState([]);
    
      useEffect(() => {
        const fetchUserDetails = async () => {
          try {
            const response = await axios.get('https://randomuser.me/api');
            const data = response.data.results;
            setUserDetails(data);
          } catch (error) {
            console.error(error);
          }
        };
        fetchUserDetails();
      }, []);
    
      console.log('!!!!!!!!!!!!!!!!!', userDetails);
    
      return (
        <>
          <UserDetails data={userDetails} />
        </>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search