Reconfigure default component props with graphql

I am trying to fetch records from a graphql backend service and render them using Array.map function. Unfortunately, while they are not loaded, I get an error because they are undefined. I tried to set default props for the component, but it didn't work. Do I need to check if everything is loaded or if there is a way to enter default values ​​in these props. My code looks like this right now

import React from 'react';
import { graphql } from 'react-apollo';
import { fetchTasks } from '../../../graphql/tasks';
import { Dashboard } from '../components/Dashboard';

const propTypes = {
    data: React.PropTypes.shape({
        tasks: React.PropTypes.array
    })
};

const defaultProps = {
    data: {
        tasks: []
    }
};

class DashboardContainer extends React.Component {
    render() {
        const titles = this.props.data.tasks.map(task => task.title);
        return(
            <Dashboard
                titles={titles}
            />
        );
    }
}

DashboardContainer.propTypes = propTypes;
DashboardContainer.defaultProps = defaultProps;

export default graphql(fetchTasks)(DashboardContainer);

      

+3


source to share


1 answer


Yes, you should check if the request has finished loading. You can walk through this nice tutorial where you create a pokemon application. The link points to the part where they show the basic query and how you check if it's loaded.

In your case, it might look like this:



import React from 'react';
import { graphql } from 'react-apollo';
import { fetchTasks } from '../../../graphql/tasks';
import { Dashboard } from '../components/Dashboard';

const propTypes = {
  data: React.PropTypes.shape({
    tasks: React.PropTypes.array
  })
};

const defaultProps = {
  data: {
    tasks: []
  }
};

class DashboardContainer extends React.Component {
  render() {
    if (this.props.data.loading) {
      return <div > Loading < /div>;
    }

    const titles = this.props.data.tasks.map(task => task.title);
    return ( <
      Dashboard titles = {
        titles
      }
      />
    );
  }
}

DashboardContainer.propTypes = propTypes;
DashboardContainer.defaultProps = defaultProps;

export default graphql(fetchTasks)(DashboardContainer);
      

Run code


+2


source







All Articles