I have app for booking. If user click to booking details btn, user can see data. Data are fetched, but useEffect is not happy.
useEffect shows me this err msg:
React Hook React.useEffect has a missing dependency: ‘getDetails’. Either include it or remove the dependency array.
I cannot remove the dependency array, it give infinitive loop, correct? So how to fix this?
I was trying put there almost everything what I have, but still got yellow underlined.
const BookedDetails = () => {
const { user } = useSelector((state) => state.userAuth)
const userID = user?.user?._id
const [details, setDetails] = React.useState([])
const [loading, setLoading] = React.useState(false)
const [invoiceLoad, setInvoiceLoad] = React.useState(false)
const [currentPage, setCurrentPage] = React.useState(1)
const [postPerPage, setPostPerPage] = React.useState(4)
const indexOfLastPost = currentPage * postPerPage
const indexOfFirstPost = indexOfLastPost - postPerPage
const currenPosts = details.slice(indexOfFirstPost, indexOfLastPost)
const pages = []
for(let i = 1; i <= Math.ceil(details.length / postPerPage); i++) {
pages.push(i)
}
const paginate = (x) => {
setCurrentPage(x)
}
const getDetails = async () => {
const config = {
headers: {
"Content-Type": "application/json",
}
}
try {
setLoading(true)
const res = await axios.post('/api/bookingDetails/bookDetails', { userID }, config )
//console.log(res.data.user)
setDetails(res.data.user)
setLoading(false)
} catch (error) {
console.log(error.message)
setLoading(false)
}
}
React.useEffect(() => {
getDetails()
},[ ]) // << dependency is yellow underlined.
>Solution :
You can define getDetails method in useEffect hook.
For example:
React.useEffect(() => {
const getDetails = async () => {
const config = {
headers: {
"Content-Type": "application/json",
},
};
try {
setLoading(true);
const res = await axios.post(
"/api/bookingDetails/bookDetails",
{ userID },
config
);
setDetails(res.data.user);
setLoading(false);
} catch (error) {
console.log(error.message);
setLoading(false);
}
};
getDetails();
}, [userID]);