import React, { useState, useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useEffectOnce } from 'usehooks-ts';
import { SportsTypeNavbar } from '../../../mobile/components'
import { getMatches } from '../../../store/actions/mobileSportsActions';
import './mHome.css'
function MHome(props) {
const dispatch = useDispatch()
const [timer, setTimer] = useState(null)
const [isMounted, setIsMounted] = useState(false)
const [sportTypeId, setSportTypeId] = useState(1);
const [betradarCategoryId, setBetradarCategoryId] = useState(0);
const [leagueName, setLeagueName] = useState();
const [matchState, setMatchState] = useState('home');
const [startIndex, setStartIndex] = useState(0);
const [orderByLeague, setOrderByLeague] = useState(false);
const get_Matches = useSelector(state => state.mobileSportsReducers.getMatches)
const SportTypeList = useSelector(state => state.mobileSportsReducers.getTypeList);
const dataFetch = () => {
console.log('sportTypeId==>', sportTypeId); // sportTypeId -> undefined
let obj = {
sportTypeId: (sportTypeId !== undefined ? sportTypeId : 1),
betradarCategoryId: betradarCategoryId,
leagueName: leagueName,
matchState: matchState,
startIndex: startIndex,
orderByLeague: orderByLeague
}
dispatch(getMatches(obj))
clearTimeout(timer)
setTimer(setTimeout(dataFetch, 5000))
}
useEffect(() => {
if (!isMounted) {
dataFetch()
setIsMounted(true)
}
})
useEffectOnce(() => {
dataFetch()
})
const sportActiveFunc = (index) => { // sending props function from parent to child component
setSportTypeId(index);
}
console.log('sportTypeId==>', sportTypeId); // output value -> 1
return (
<SportsTypeNavbar sportActiveFunc={sportActiveFunc} />
)
};
export default MHome;
I am trying to set the value from state on this component for sending value by dispatch to server. This value is coming from child component via sportActiveFunc function. So here, I can get sportTypeId, but I can't get this state value on dataFetch function. How can I get this state value?
In your useEffect, call the dataFetch
method only when the sportTypeId
is set
useEffect(() => {
if (!isMounted && sportTypeId) {
dataFetch()
setIsMounted(true)
}
}, [sportTypeId])
you can simply pass that as props in sportActiveFunc funtion and have default value for it
like this:
const dataFetch = (id = sportTypeId ) => {
let obj = {
sportTypeId: id ,
betradarCategoryId: betradarCategoryId,
leagueName: leagueName,
matchState: matchState,
startIndex: startIndex,
orderByLeague: orderByLeague
}
dispatch(getMatches(obj))
clearTimeout(timer)
setTimer(setTimeout(dataFetch, 5000))
}
const sportActiveFunc = (index) => {
setSportTypeId(index);
dataFetch(index)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.