-1

My code below, i am getting the error in the heading of this post. it must be something simple can you guys advise?

import {useEffect, useState} from 'react'
import axios from 'axios'
import XMLParser from 'react-xml-parser'
import AuthorList from '../components/AuthorList'

function Home() {
    const [authors, setAuthors] = useState([])
    useEffect(async function() {
    var data = await axios.get("http://localhost:8080")
    var xml = new XMLParser().parseFromString(data.data)
    var formattedData = xml.children.map(function(author) {
        return {
            author_name: author.children[0].value,
            title: author.children[1].value,
            year: author.children[2].value
        }
    })
    setAuthors(formattedData)
}, [])

return(
    <div>
        <AuthorList authors={authors} />

    </div>
    )
}

export default Home

error message: enter image description here

georgieboy
  • 155
  • 1
  • 10
  • Does this answer your question? [React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing](https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret) – Terry Apr 15 '22 at 21:55
  • Can you add the error message, so we can give you proper help? – Amr Apr 15 '22 at 21:56

2 Answers2

0

Marking a function as async is the same as returning a promise from that function. You can't do this with useEffect because it expect the return type of the callback to be a function. What you can do is create an async function inside and call it immediately as the error message suggest.

useEffect(() => {
  (async function() {
    var data = await axios.get("http://localhost:8080")
    var xml = new XMLParser().parseFromString(data.data)
    var formattedData = xml.children.map(function(author) {
        return {
            author_name: author.children[0].value,
            title: author.children[1].value,
            year: author.children[2].value
        }
    })
    setAuthors(formattedData)
  })()
}, [])
Konrad
  • 21,590
  • 4
  • 28
  • 64
0

useEffect callbacks should not be async. Wrap your logic inside an async IIFE like this:

useEffect(() => {
    (async () => {
        var data = await axios.get("http://localhost:8080")
        var xml = new XMLParser().parseFromString(data.data)
        var formattedData = xml.children.map(function(author) {
            return {
                author_name: author.children[0].value,
                title: author.children[1].value,
                year: author.children[2].value
            }
        })
        setAuthors(formattedData)
    })();
 }, [])

The technical reason for the error is that async functions return a Promise and React expects a callback to be called on cleanup.

Asplund
  • 2,254
  • 1
  • 8
  • 19