I have the following problem:
I currently have an app configured with react that consumes a service through graphql with apollo, I tested in graphiql that the service worked (the user must be authenticated) but now that I pass the queries to the front and call the service, it returns me user must be authenticated
.
It is as if at the time of making a request it did not recognize that the user is authenticated, when I checked the configuration of index.js
the variable authLink
I could see that the headers setContext
arrived undefined
:
// 1
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
// 2
const httpLink = createHttpLink({
uri: config.url.API_URL
});
// 3
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}` : "",
}
}
});
// 4
export const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
})
The service in the view is configured as follows:
// React
import React from 'react';
// Components
import SearchBar from '../../../components/searchbar';
import Books from '../../../components/books';
// React apollo
import { graphql } from 'react-apollo';
import compose from 'lodash.flowright';
// Queries
import queries from './queries';
// Style
import './style.sass';
class BookHome extends React.Component {
constructor(props) {
super(props);
this.state = {
books: []
}
this.getBooks();
}
getBooks = () => {
const { getBooks } = this.props;
console.log(this.props);
}
render() {
return(
<div className="books-home-container">
<div className="books-header-home"></div>
<SearchBar />
<Books />
</div>
);
}
}
export default compose(
graphql(queries.getBooks, { name: 'getBooks' })
)(BookHome);
And the variable queries that is called from the view (from above):
import gql from 'graphql-tag';
const queries = {
getBooks: gql`
query {
bookList {
id
coverImage
title
author
rating
}
}
`,
}
export default queries;
After seeing the code with a colleague, we were able to arrive at the solution. These lines were missing in the method
current_user
: