skip to Main Content

I’m getting this error back though this same format seems to work in examples.

    const response = await axios.get('http://localhost:5000/get-tasks')

    const dataObject = response.data
    

    const arrayOfKeys = Object.keys(dataObject)
    const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key])

    console.log(arrayOfKeys)
    console.log(arrayOfData)
  }, [])```

2

Answers


  1. async functions return a Promise, and useEffect does not expect a Promise returned. (If anything is returned at all, it should be a function for cleanup of any effects when a component is unmounted.)

    If you want to use async/await in useEffect then you can wrap the whole thing in an async IIFE. For example:

    useEffect(() => {
      (async () => {
        const response = await axios.get('http://localhost:5000/get-tasks');
        const dataObject = response.data;
    
        const arrayOfKeys = Object.keys(dataObject);
        const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key]);
    
        console.log(arrayOfKeys);
        console.log(arrayOfData);
      })();
    }, []);
    

    Alternatively, you can use .then() on the inner async operation instead of await:

    useEffect(() => {
      axios.get('http://localhost:5000/get-tasks').then(response => {
        const dataObject = response.data;
    
        const arrayOfKeys = Object.keys(dataObject);
        const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key]);
    
        console.log(arrayOfKeys);
        console.log(arrayOfData);
      });
    }, []);
    
    Login or Signup to reply.
  2. The useEffect function arg can’t be asynchronous, but you can call an async function inside it.

    useEffect(() => {
      async function getTasks() {
        const response = await axios.get('http://localhost:5000/get-tasks')
    
        const dataObject = response.data
    
        const arrayOfKeys = Object.keys(dataObject)
        const arrayOfData = Object.keys(dataObject).map((key) => dataObject[key])
    
        console.log(arrayOfKeys)
        console.log(arrayOfData)
      };
    
      getTasks();
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search