Home > database >  How to get an asynchronous request from the server using Hook useEffect?
How to get an asynchronous request from the server using Hook useEffect?

Time:03-28

Here's how I tried to do it, but it didn't work

    useEffect(() => {
    try {
        const response = async() => {
            await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
        console.log(response.data)
    } catch (e) {
        console.log(e);
    }   
})

And so it should look in class components

    async componentDidMount() {
    try {
        const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
        
        console.log(response.data)
    } catch (e) {
        console.log(e);
    }
}

CodePudding user response:

I believe you forgat to use the response to convert it to a useable data

useEffect(() => {
    try {
        const response = async() => {
        await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
        const dataUser = await response.json(); //THIS LINE
        console.log(dataUser)
    } catch (e) {
        console.log(e);
    }   
})

And so it should look in class components

async componentDidMount() {
    try {
        const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
        const dataUser = await response.json(); //THIS LINE
        console.log(dataUser)
    } catch (e) {
        console.log(e);
    }
}

I got a few examples in this Github repository

CodePudding user response:

you must define a function and call it after

useEffect(() => {
    const fetchData=async()=>{
    try {
        const response = async() => {
            await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')}
        console.log(response.data)
    } catch (e) {
        console.log(e);
    }
  };
  fetchData();
})

CodePudding user response:

You are defining your response as a function (that is never used) rather to do a request call . Maybe this is the correct way to do what you want.

useEffect(async () => {
  try {
    const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')
    console.log(response.data)
  } catch (e) {
     console.log(e);
  }   
})

If it don't works, try to split you request function and the useEffect like this (maybe the useEffect don't permit async functions as its parameter).

async function request(){
  const response = await axios.get('https://prectik-87c20-default-rtdb.europe-west1.firebasedatabase.app/quizes.json')
  console.log(response.data)
}
useEffect(async () => {
  try {
    request()
  } catch (e) {
     console.log(e);
  }   
})
  • Related