Catalin A.
Catalin A.

Reputation: 19

Use React Hooks to fetch data from MySQL with Axios

I have this problem and I hope that you'll be able to help me. So, I've created a React Hook to fetch data from my MySQL database. The code written for the hook is presented below:

const useMySQLToView = (table) => {
    const [rows, setRows] = useState([])

    useEffect(() => {
        async function fetchData() {
            const result = await axios.get("http://localhost:4999/get"+table)
            setRows(result)
        }
        fetchData()
    }, [table])

    return rows
}

Then I tried to get data using the hook on my component:

function ViewEmployees() {
    const {employees} = useMySQLToView('Employees')
    console.log(employees)
    return (
        <div>
            View employees
        </div>
    )
}

The problem is that this console.log(employees) returns undefined. Do you know why? How can I fix this? Thank you!

Upvotes: 0

Views: 811

Answers (1)

thedude
thedude

Reputation: 9812

Replace const {employees} = useMySQLToView('Employees') with

const employees = useMySQLToView('Employees')

Since your hook is simply returning rows and not an object you can destructure

Upvotes: 1

Related Questions