At loss when it comes to a reusable component I am making in React. The purpose of the component is to get API data and send it to parent where the data in mapped in cards. The component should also be able to receive a function call from the parent that is used to 'load more' data and props which to set whether I search old / new data.
I haven't been able to figure the best way to achieve this or whether I should do it that I through props.children I would display the cards inside the child, hence no need to send data upwards.
Parent:
function Page() {
const [eventData, setEventData] = useState([]);
const EventCardUpcoming = () => {
const filterRef = useRef(null);
const handleClick = () => {
filterRef.current.callLoad();
};
const setData = () => {
setEventData()
}
return (
<InfiniteScroll
pageStart={0}
hasMore={true || false}
loadMore={handleClick}
>
<button onClick={handleClick}>Load more</button>
<Row className="py-4">
<div>
<EventFiltering
OrganizerId={"1"}
ref={filterRef}
sendData={setData()}
/>
</div>
{eventData ?
<div>
{eventData.map((v, i) => (
<Col key={i} xs={12} sm={12} md={6} lg={4} xl={3}>
<div className="d-flex justify-content-center">
<>
<EventCard eventData={v} />
</>
</div>
</Col>
))}
</div>
: null}
</Row>
</InfiniteScroll>
);
};
return (
<Container>
<EventCardUpcoming />
</Container>
);
}
export default Page;
Filtering child component:
const Filtering = forwardRef((props, ref, { sendData }) => {
const staticOrganizer = props.OrganizerId; //API configurable option
const paramLimit = 4;
const [eventData, setEventData] = useState([]);
let params = {
org: staticOrganizer,
limit: paramLimit,
};
useImperativeHandle(ref, () => ({
callLoad() {
handleLoadMore(); //load more data from function called in parent
},
}));
useEffect(() => {
sendData(data); //send data to parent when more is fecthed
}, [eventData]);
const handleLoadMore = () => {
APIGet("getData", params).then((res) => {
if (res.data.body.length > 0) {
setEventData((eventData) => eventData.concat(res.data.body));
}
});
};
return (
<Container>
<div>
<Dropdowns />
</div>
</Container>
);
}
);
export default Filtering;
CodePudding user response:
Lose the parenthesis
sendData={setData}
update setMethod to accept data as param
const setData = (data) => {
setEventData(data)
}