Reputation: 604
I want to call child function from parent and set state of a child's hook ,but I cant able to success it ,simple code is below ,setstate isnt working inside useImperativeHandle.Any help is appreciated ,thx..
const child = forwardRef((props,ref) => {
const [pagerTotalCount, setPagerTotalCount] = useState(0);
const [customerData, setCustomerData] = useState([]);
useImperativeHandle(ref, () => ({
childFunction1: updatePagerTotalCount;
}));
})
const updatePagerTotalCount = (param) => {
setPagerTotalCount(param); // this IS working now...
const pagerInputModel = {
"pageNumber": 1,
"pageSize": 3,
};
myservice.listCustomerList(pagerInputModel).then((res) => {
const { isSuccess, data: customers} = res;
if (isSuccess) {
console.log("api result:" + JSON.stringify(customers)); // this IS working,api IS working
setCustomerData(customers); // this IS NOT working , cant SET this.
console.log("hook result:" + JSON.stringify(customerData)); //EMPTY result.I tested this WITH another buttonclick even IN ORDER TO wait FOR async,but still NOT working
}
});
};
const parent= () => {
const childRef = React.useRef(null)
const handleClick = () => {
childRef.current.childFunction1(11); //sending integer param to child
};
RETURN(
<>
<Button variant="contained" endIcon={<FilterAltIcon />} onClick={handleClick}>
Filtrele
</Button>
<child ref={childRef}/>
</>
)
}
Upvotes: 0
Views: 2059
Reputation: 10849
You should define a function to update the state and return that function via useImperativeHandle
.
const updatePagerTotalCount = (param) => {
setPagerTotalCount(param);
};
useImperativeHandle(ref, () => ({
childFunction1: updatePagerTotalCount;
}));
Now with above when childRef.current.childFunction1(11);
is invoked via parent component, you can see the state is being set correctly.
Upvotes: 1