I am trying to setState() to a query result I have from graphQL, but I am having difficulty finding out how to do this because it will always be loading, or it\'s only used from
A simple solution is to separate your Apollo query components and React stateful components. Coming from Redux, it's not unusual to transform incoming props for local component state using mapStateToProps
and componentWillReceiveProps
.
However, this pattern gets messy with Apollo's
.
So simply create a separate component which fetches data:
...
export class WidgetsContainer extends Component {
render (
{({ loading, error, data }) => {
if (loading) return ;
const { widgets } = data;
return (
)
}}
)
}
And now the Widgets
components can now use setState
as normal:
...
export class Widgets extends Component {
...
constructor(props) {
super()
const { widgets } = props;
this.state = {
filteredWidgets: widgets
};
}
filterWidget = e => {
// some filtering logic
this.setState({ filteredWidgets });
}
render() {
const { filteredWidgets } = this.state;
return (
{filteredWidgets.count}
)
}
}