Reputation: 1251
I have a custom hook for reusing UseEffect
import {useState, useEffect } from 'react'
export default function useGetList(getListFunc) {
const [currentList, setCurrentList] = useState([]);
useEffect(() => {
async function fetchData() {
setCurrentList(await getListFunc())
}
fetchData();
}, [getListFunc]);
return currentList
}
I can use this custom hook in a component directly.
const currentStaff1 = useGetList(getStaffListFunc)
console.log(currentStaff1)
But using it to set the default value of a state variable is giving an empty array []
const [currentStaff, setCurrentStaff] = useState(useGetList(getStaffListFunc))
console.log(currentStaff)
What is wrong here?
Upvotes: 0
Views: 571
Reputation: 1094
you could try this
const [currentList, setCurrentList] = useState([]);
useEffect(() => {
async function fetchData() {
setCurrentList(await getListFunc())
}
fetchData();
}, [getListFunc]);
return [currentList] // return as array
and then in your component
const [currentStaff] = useGetList(getStaffListFunc)
Upvotes: 1
Reputation: 1251
I moved useEffect directly into the component, rather than the reusable custom hook, after realizing a state hook was used inside another statehook.
Upvotes: 0