0
votes

I have a react-redux app that uses Apollo client to make queries to my api GraphQL.

I have a GridContainer that makes the query call using export default connect(mapStateToProps, mapDispatchToProps)(GridContainerWithData); where GridContainerWithData is a const that makes the query with graphql(gql`...)

This returns data in my props containing: the query response, if there is an error and the loading state (true or false).

Right now, I'm managing the loading myself using if(loading) {}.

The problem in this is my component renders when it's in loading state and then again when the query is done loading. If I don't use the if(loading) {}, I get an error saying I need to return something when the query is in loading state.

Is there any way to tell the component to not render when the query is loading?

I tried using

shouldComponentUpdate (nextProps) {
    if (this.props.data.loading !== nextProps.data.loading) {
      console.log(‘i will rerender’, nextProps.data.loading);
      return true;
    }else {
      return false;
    }
}

but no luck there.

Is there any way to tell the component to not render when the query is loading?

EDIT:

This is my GridContainer if it can help anyone.

class ActionsToDoGridContainer extends Component {

 render () {
   const {error} = this.props.data;

   if (error) {
     return (
       <div className='ComponentDistance'>
         An unexpected error happened :
         {error}
       </div>);
    } else {
     return (
        <div className='ComponentDistance'>
          <ActionsToDoGrid {...this.props}/>
         ActionsToDoButtons {...this.props}/>
        </div>
     );
    }
  }
}
1

1 Answers

2
votes

edit: The poster of the question resolved his own issue with this code:

shouldComponentUpdate(nextProps) { 
  if (nextProps.data.loading === false) { 
    return true;
  } else {
    return false;
  }
}

I think you were thinking in the right direction with shouldComponentUpdate, but instead of checking to see if the loading state is different, check to see if your data is different.

shouldComponentUpdate (nextProps) {
    const thisData = this.props.data.queryDataResponse;
    const nextData = nextProps.data.queryDataResponse;
    if (!someLibrary.deepEquals(thisData, nextData)) {
      return true;
    }else {
      return false;
    }
}

If the data changes, your function will return true and update. You may run in to some edge cases so don't forget about this function when things seem to break