如何在React Apollo中的查询变量中传递全局函数值

时间:2019-03-01 10:05:14

标签: reactjs graphql react-apollo apollo-client next.js

你好,我正在尝试使用apollo react在查询变量中传递全局函数值,但没有获得值。

import jwtDecode  from 'jwt-decode';
const tokenKey = 'token';


export function logout(){
    localStorage.removeItem(tokenKey);
}

export function getCurretUser (){
    try{
        const jwt = localStorage.getItem(tokenKey);
        return jwtDecode(jwt);
      }
      catch(ex) {
          return null;
      }
}

export function getJwt(){
    return  localStorage.getItem(tokenKey);
 }

export default {
    logout,
    getCurretUser,
    getJwt

}

我在render方法中获得了全局函数值,但我想将其传递到外部render方法中。

    import React, { Fragment } from 'react';
import { css } from 'emotion';
import Head from 'next/head';

import { Button, Container, Input, H2, Grid, GridCell } from '../primitives';
import { Redirect } from '../components/Router';

import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import auth from '../components/authservice';



 class FavouriteJob extends React.Component {
//state = { loginUserId: '' };
static async getInitialProps({ auth }) {
    const getCurretUser  = await auth.getCurretUser(auth.getCurretUser);
    return getCurretUser;
}

onFavouriteJobDelete(jobid) {
    this.props
        .mutate({ variables: { jobid } })
        .then(() => this.props.data.refetch());
}

renderFavouriteJobs() {
    return this.props.data.getUserById.favourite.map(({ id, title }) => {
        return (
            <li key={id} className="collection-item">
                {title}
                <i
                    className="material-icons"
                    onClick={() => this.onFavouriteJobDelete(id)}
                >
                    Remove
                </i>
            </li>
        );
    });
}


render() {
        console.log(this.props);
        console.log(getCurretUser);
        if (this.props.data.loading) {
            return <div> Loading...</div>;
        }

        return (
            <Container>
                <div>
                    <ul className="collection">{this.renderFavouriteJobs()}</ul>
                </div>
            </Container>
        );
    }
}

const query = gql`
    query getUserById($id: ID!) {
        getUserById(id: $id) {
            username
            email
            phone
            favourite {
                id
                title
                description
                source
                logo
                suburb
                label
            }
        }
    }
`;

const mutation = gql`
    mutation removeFavouriteJob($jobid: ID!) {
        removeFavouriteJob(jobid: $jobid) {
            username
        }
    }
`;

export default graphql(mutation)(
    graphql(query, {
        options: props => ({ variables: { id: '5c73e07fef69a470c8785455' } }),
    })(FavouriteJob)
);

任何人,请提出可能的解决方案以解决此问题。

谢谢

0 个答案:

没有答案