Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component default props with graphql

I'm trying to fetch records from backend graphql service and render them with Array.map function. Unfortunately before they're loaded I get error because they are undefined. I tried to set default props on component but it didin't work. Do i have to check if everything is loaded or is there specific way to inject default values into those props. My code looks like that 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);
like image 910
ruciu Avatar asked Jan 31 '26 07:01

ruciu


1 Answers

Yes you have to check if the query has finished to load. You could go through this nice tutorial, where you build a pokemon app. The link points to the part where they show a basic query and how you check if it is loaded.

In your case it could 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);
like image 105
Locco0_0 Avatar answered Feb 02 '26 02:02

Locco0_0