Home > Net >  useEffect must not return anything besides a function error
useEffect must not return anything besides a function error

Time:04-16

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

CodePudding user response:

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)
  })()
}, [])

CodePudding user response:

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.

  • Related