带有Apollo的Gatsby给出错误,因为客户端在查询中未定义

时间:2018-08-21 05:46:31

标签: reactjs graphql apollo gatsby

我的组件也使用gatsby ...

import React, { Component } from 'react'
import Link from 'gatsby-link'
import axios from 'axios'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import { Query } from 'react-apollo'

export const IndexQuery = gql`
{
  allsingleCsv {
    make
    model
    image
    _variant
    ex_showroom_price
    path
}
}`

class CarTemplatePage extends Component {
  constructor(){
    super()
    this.state = {
      name : '',
      number : 0,
      emailId : ''
    }
    this.handleSubmit = this.handleSubmit.bind(this)
    this.onNameChange = this.onNameChange.bind(this)
    this.onNumberChange = this.onNumberChange.bind(this)
    this.onEmailChange = this.onEmailChange.bind(this)
  }
  handleSubmit(e){
    e.preventDefault();
    const data = new FormData();
    data.append("user_id", "44");
    data.append("city", "Bangalore");
    data.append("lead_category_id", "1");
    data.append("lead_type_id", "1");
    data.append("lead_source_id", "3");
    data.append("make_id", "11");
    data.append("model_id", "11");
    data.append("vehicle_id", "601");
    data.append("services_id", "1");
    data.append("status", "0");

    const header = {
        'Authorization': 'Bearer '+localStorage.getItem('access_token')
    }

    axios({
      url: 'http://localhost:8000/v1/dealers/leads',
      method: 'post',
      headers: header,
      data: data
    }).then((result) => {
      console.log(result.data)
    });
  }

  onNameChange(event) {
    this.setState({ name: event.target.value });
  }

  onNumberChange(event) {
    this.setState({ number: event.target.value });
  }

  onEmailChange(event) {
    this.setState({ emailId: event.target.value });
  }

  render() {
    const IMAGE_URL = 'https://s3.ap-south-1.amazonaws.com/carsonline.in/';
    // const data = [...this.props.data.allsingleCsv]

    return (

             <Query ssr={true} query={IndexQuery}>
               {({loading, error, data}) => {
                    if (loading) return null;
                    if (error) throw err;
                   return console.log(data);
                }}
            </Query>

        </div>



<form onSubmit={this.handleSubmit} className='container'>
<div className="form-group">
  <label for="Name">Name:</label>
  <input type="Name" className="form-control" id="Name" onChange={this.onNameChange} value={this.state.name}/>
</div>
<div className="form-group">
  <label for="Contact Number">Contact Number:</label>
  <input type="Contact Number" className="form-control" id="contactNumber" onChange={this.onNumberChange} value={this.state.number}/>
</div>
<div className="form-group">
  <label for="Email Id">Email ID:</label>
  <input type="Email Id" className="form-control" id="EmailId" onChange={this.onEmailChange} value={this.state.emailId}/>
</div>
<button type="submit" className="btn btn-default">Submit</button>
</form>
      </div>


    )
  }
}
export default CarTemplatePage;

这是gatsby ssr

/**
 * Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/ssr-apis/
 */

 // You can delete this file if you're not using it
 import React from "react";
 import { renderToString } from "react-dom/server";
 import ApolloClient, { createNetworkInterface } from "apollo-client";
 import { ApolloProvider, getDataFromTree } from "react-apollo";
 import { ServerStyleSheet, StyleSheetManager } from "styled-components";
 import { HttpLink } from 'apollo-link-http';
 import { ApolloLink } from 'apollo-link';

 // function to generate hydrated state for client side Apollo
 function makeApolloState(ssrClient) {
   const state = { apollo: ssrClient.getInitialState() }
   // appends apollo state to the global client window object
   return (
     <script
       dangerouslySetInnerHTML={{
         __html: `window.__APOLLO_STATE__=${JSON.stringify(state).replace(
           /</g,
           `\\u003c`
         )};`
       }}
     />
   );
 }

//appollo setup
const link = new HttpLink({ uri: '/graphql' });
 // Apollo client in server side rendering mode
 const client = new ApolloClient({
   link,
   ssrMode: true,
   dataIdFromObject: o => o.id
 });

 exports.replaceRenderer = ({
   bodyComponent,
   replaceBodyHTMLString,
   setHeadComponents
 }) =>
   new Promise((resolve) => {
     // bodyComponent is the entire React component tree for the page
     /*
       to remove styled components:
       1. remove const sheet
       2. remove StyleSheetManager
       3. remove sheet.getStyleElement from setHeadComponents array
     */
     const sheet = new ServerStyleSheet()
     const ApolloQueries = (
       <ApolloProvider client={client}>
         <StyleSheetManager sheet={sheet.instance}>
           {bodyComponent}
         </StyleSheetManager>
       </ApolloProvider>
     );
     // getDataFromTree walks ApolloQueries tree for all Apollo GQL queries
     // It runs the queries and mutates client object
     getDataFromTree(ApolloQueries).then(() => {
       // renders ApolloQueries to string and then inserts it into the page
       replaceBodyHTMLString(renderToString(ApolloQueries))
       // sets head components with styled components and apollo state
       setHeadComponents([sheet.getStyleElement(), makeApolloState(client)])
       resolve();
     })
   })

显示的错误

index.js:2177 Warning: Failed context type: The context `client` is marked as required in `Query`, but its value is `undefined`.
    in Query (at allCars.js:105)
    in div (at allCars.js:81)
    in div (at allCars.js:78)
    in CarTemplatePage (created by ComponentRenderer)
    in ComponentRenderer (created by Route)
    in Route (created by Layout)
    in div (at index.js:24)
    in div (at index.js:9)
    in Layout (at index.js:6)
    in _default (created by ComponentRenderer)
    in ComponentRenderer (created by Route)
    in Route (created by withRouter(ComponentRenderer))
    in withRouter(ComponentRenderer) (created by Root)
    in ScrollContext (created by Route)
    in Route (created by withRouter(ScrollContext))
    in withRouter(ScrollContext) (created by Root)
    in Router (at root.js:151)
    in DefaultRouter (created by Root)
    in Root (at app.js:51)
    in AppContainer (at app.js:50)

I just want to render out the data coming from a csv file

我还创建了客户端对象,但是仍然不确定,我该如何解决此问题。我也知道gatsby并不正式支持apollo,但是我想在组件中运行查询,因此我需要使用apollo在github中找到gatsby ssr文件hack。请帮助并感谢您的关注

1 个答案:

答案 0 :(得分:0)

尝试使用Gatsby V2,StaticQuery组件类似于 Apollo Client

来自https://next.gatsbyjs.org/docs/static-query/#basic-example的示例:

import React from 'react';
import { StaticQuery, graphql } from 'gatsby';

export default () => (
  <StaticQuery
    query={graphql`
      query HeadingQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (
      <header>
        <h1>{data.site.siteMetadata.title}</h1>
      </header>
    )}
  />
);