Reputation: 455
Sorry if this question displays a lack of understanding of the react paradigm which I suspect it does however I am very new to the tech.
I want to dispatch an action from my 'actions' code which should ultimately call a function on a nested component. Up to now I have been simply modifying state by dispatching actions and catching them in the reducer which works fine.
I am working on a portlet as part of a wider framework and I can capture an onExport() message in the actions. From here I have no idea of the best way to call the nested component (I need access to the inner ag-grid in the nested component to export it).
I have considered introducing some new 'exportRequested' state flag and setting this in the reducer then using componentDidReceiveProps in the nested component. I have also been studying the 'connect' idea and this seems right in so far as it would allow me to expose the function and connect it to the store but I can't seem to join the dots and figure out how to invoke it from the reducer. Is there some way to sort of dispatch an action and catch it directly in the nested component?
some code:
Container:
import {initData} from '/actions';
export class MainComponent extends PureComponent {
static propTypes = {
initData: func.isRequired,
data: array.isRequired,
};
static defaultProps = {
data: [],
};
componentDidMount() {
this.props.initData();
}
render() {
const { data } = this.props;
return (
<div>
<ChildGrid data={data} />
</div>
);
}
}
export default connect(
state => ({
data: getData(state),
}),
{ initData }
)(MainComponent);
Nested Grid:
export class ChildGrid extends PureComponent {
static propTypes = {
data: array.isRequired,
};
static defaultProps = {
data: [],
};
exportData() {
// HOW TO MESSAGE THIS FROM ACTIONS. I want to call DataGrid.gridApi.exportAsCsv()
}
render() {
const { data } = this.props;
return (
<div>
<DataGrid
rowData={data}
/>
</div>
);
}
}
Upvotes: 0
Views: 57
Reputation: 1442
You thought of the correct solution to your problem, by creating a state flag in your redux store then listening to the change of that property in your nested component. Unfortunately in Redux we can't listen to specific events or specific state property changes of the Redux store.
The implementation of such a solution is as follows:
ChildGrid.jsx
class ChildGrid extends PureComponent {
static propTypes = {
data: array.isRequired,
};
static defaultProps = {
data: [],
};
componentWillReceiveProps(newProps) {
if (newProps.exportRequested) {
this.exportData();
}
}
exportData() {
DataGrid.gridApi.exportAsCsv();
}
render() {
const { data } = this.props;
return (
<div>
<DataGrid
rowData={data}
/>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
reduxExportRequested: state.exportRequested
};
};
export default connect(mapStateToProps)(ChildGrid);
Upvotes: 1