Gabriel Donada
Gabriel Donada

Reputation: 449

useEffect and Axios getting a null json

I built a react code using useEffect()and Axios to get a json from an URL, however I'm getting an empty array, probably because it is not async function. Here is my code:

import axios from "axios";
import { useEffect, useState } from "react";



export function UseVacation (){
    const[vacations, setVacations] = useState([]);

    useEffect(() =>{

        axios.get('APILINK').then( async (res) =>{
            
            setVacations(res.data);

            console.log("vactest: "+ JSON.stringify(vacations))

        }).catch((err)=>{
            alert("Error extracting the data from API: "+err);
        })

    }, [])

    return (
        <div>
            
                {vacations.map( (vac) => {
                    <h1>{vac._id}</h1>
                })}
            
        </div>
    )

}

Any idea on this?

Upvotes: 0

Views: 806

Answers (4)

Gabriel Donada
Gabriel Donada

Reputation: 449

I've changed my return and it fixed issue. Why? I don't know, but is working:

return (
    <div>
        {vacations.map( (vac) => {
            return(
                <h1>{vac?._id}</h1>
            )
        })}
    </div>
)

Upvotes: 1

tran dinh thang
tran dinh thang

Reputation: 29

I have good suggestion for you:

const[vacations, setVacations] = useState([]);
useEffect(() => {
  const getApi = async () => {
    try {
      const res = await axios.get('APILINK')
      setVacations(res.data);      
    } catch(error) {
      console.log(error)
    }                
  }
  getApi()
}, [])
console.log("vactest: "+ vacations)

I cannot explain but if you set state in useEffect and direct log state in useEffect, it only log previous state

Upvotes: 0

sweenejp
sweenejp

Reputation: 61

Have you tried the following?

return (
    <div>
        
            {vacations && vacations.map( (vac) => {
                <h1>{vac._id}</h1>
            })}
        
    </div>
)

Upvotes: 0

Satwinder Singh
Satwinder Singh

Reputation: 229

Why dont you console res.data instead of vacations and see what it has ? Also check the network tab, and see what actual request has in the response

Upvotes: 1

Related Questions