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
})
});