How to setState() in React/Apollo with graphQL

前端 未结 3 1763
醉话见心
醉话见心 2021-02-04 20:14

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

3条回答
  •  广开言路
    2021-02-04 20:52

    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}
    ) } }

提交回复
热议问题