How to use data from readFragment in Apollo?

爷,独闯天下 提交于 2019-12-10 23:37:45

问题


After a login mutation, a jwt token and a user object (id and firstName) are returned and stored in cache (as shown in the image below).

I want to retrieve the user informations from the cache by using readFragment and pass it to Layout component.

So I've tried to use read Fragment in my Layout component like this :

class Layout extends Component {

  render() {
    const test = this.props.client.readFragment({
      id: 1, // `id` is any id that could be returned by `dataIdFromObject`.
      fragment: gql`
        fragment user on User {
          id
          firstName
        }
      `
    });

    return (
      <div>
        <AppBar
          title="myApp"
        />
        <Sidebar
          //   firstName={this.props.data.firstName}
        />
        {this.props.children}
      </div>
    );
  }
}

export default withApollo(withRouter(Layout));

The issue here is that I don't know how to pass data from readFragment result (when I try to console.log "test" the result is undefined). But when I add a non existing field in the fragment query I have the following message :

This error is normal but proves that readFragment can read the user informations.

So how to use data from readFragment in my Layout component ?

Thanks for your help.

EDIT : Here is my ApolloClient configuration :

const httpLink = createHttpLink({
  uri: "http://127.0.0.1/graphql"
});

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) history.push("/erreur", { errors: graphQLErrors });

  if (networkError) history.push("/erreur", { errors: networkError });
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem("token");
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
});

const link = ApolloLink.from([errorLink, authLink, httpLink]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache({
    dataIdFromObject: object => object.id
  })
});

回答1:


Finally it's working now. I've updated all my npm dependencies and it seems that it was the source of the issue. For those that are interested, here is the code :

const data = this.props.client.readFragment({
      id: 1, // `id` is any id that could be returned by `dataIdFromObject`.
      fragment: gql`
        fragment user on User {
          id
          firstName
        }
      `
    });

    if(data)
      console.log(data.id);

The drawback here is that you need the id returned by dataIdFromObject, in my case it's the user id.

If you want to use your data you have just to control that the data variable is not null and then you can use the informations that you need to display.



来源:https://stackoverflow.com/questions/49025250/how-to-use-data-from-readfragment-in-apollo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!