Home > Software design >  Axios.get() request returning undefined
Axios.get() request returning undefined

Time:12-12

In the below code Iam trying to use axios get request from await axios.get('/products/api') is only working i can see the data in the console but forawait axios.get('/users/api')Undefined is being returned on the console but when i try get request through Postman i can get the results .Iam stuck here.

''' const [userdata, setuserdata] = useState([]); const [products, setproducts] = useState([]);

useEffect(() => {
    const fetchUserData = async () => {
        
        const { users } = await axios.get('/users/api')
        setuserdata(users);

        const { data } = await axios.get('/products/api')
        setproducts(data);
    }
    fetchUserData();



}, []);
console.log(products)
console.log(userdata)

CodePudding user response:

Update your code to this:

   const users = await axios.get('/users/api')
    setuserdata(users.data);

    const products = await axios.get('/products/api')
    setproducts(products.data);

CodePudding user response:

Before you destructure your response console.log the response. I mean try:

const users = await axios.get('/users/api');
console.log(users)

It could be that users is not part of the default axios data object. If you still get undefined, then you need to double check that your api is returning the response (POSTMAN).

CodePudding user response:

Believe what you're trying to do is:

const [userdata, setUserData] = useState([])
const [products, setProducts] = useState([])

useEffect(() => {
    const fetchUserData = async () => {
        const users = await axios.get('/users/api')
        setUserData([...userdata, users])

        const data = await axios.get('/products/api')
        setProducts([...products, data])
    }
    fetchUserData()
}, [userdata, products])

console.log(products)
console.log(userdata)

If you just use [] on the useEffect it will only run once at the beginning but per memory React will throw a warning for products and userdata.

Think they'd also work better in their own useEffect. You could even make your code cleaner by creating a function and passing the path in to the function. Like:

const getData = async (path) => await axios.get(`/${path}/api`)
  • Related