Why there is no data after the first login? - vuex

Dear vue and apollo users;
I am dealing with the first time install problem.
When I first launch the app, I don't get results.
I am using ApolloClient, InMemoryCache, HttpLink from "apollo-boost"
I store my userID and JWT in ApplicationSettings(local storage)
How to set token dynamically?
Vue.use(VueApollo);
const httpLink = new HttpLink({
uri: "https://sebapi.com/graphql"
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from ApplicationSettings if it exists
var tokenInAppSettings = ApplicationSettings.getString("token");
// return the headers to the context so HTTP link can read them
return {
headers: {
...headers,
authorization: tokenInAppSettings
? `Bearer ${tokenInAppSettings}`
: null
}
};
});
export const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
const apolloProvider = new VueApollo({
defaultClient: apolloClient
});
I have created a GitHub repo reproducing problem
and a youtube video of the problem
There is no error during login but after navigating to the list page for the first time I got following errors...
JS: [Vue warn]: Invalid prop: type check failed for prop "items". Expected Array, Object, got Undefined
JS: Error sending the query 'birds' ServerError: Response not successful: Received status code 400
IT SEEMS APOLLO DOES NOT HAVE userID during first query.
NOTE: You can easily clear user data by using yarn cl script
# debug app without HMR
yarn devn
# clear user data of app
yarn cl

Solution repo using vuex:
https://github.com/kaanguru/data-firstlogin/tree/user-in-vuex
Move userID into vue instance
+welcome.vue+
//const userId = ApplicationSettings.getNumber("userID");
// I have moved userID into vue.
export default {
data() {
return {
birds:[],
bird:{
id: null,
isim: "",
bilezik: ""
},
userId: ApplicationSettings.getNumber("userID")
};
},
apollo: {
birds: {
query: gql`
query myBirds($userId: ID!) {
birds(where: { user: $userId }) {
id
isim
bilezik
}
}
`,
variables() {
return {
userId: this.userId,
};
},
},
},
};

Related

Response not sucessful:Recevied status code 500 using apolloclient graphql reactNative

when put token value as hardcoded it's work properly,but when i got token from asyncstorage and pass token in headers i got this error
Response not sucessful:Recevied status code 500 What is wrong in mycode?
import { ApolloClient,ApolloProvider,InMemoryCache,gql } from '#apollo/client'
import { createUploadLink } from 'apollo-upload-client'
const getToken = async () => {
const token = await AsyncStorage.getItem('#storage_Key')
return token
}
const token = getToken()
const client = new ApolloClient({
link: createUploadLink({
uri: 'http://192.168.1.82:8080/graphql',
headers: {
authorization: token
}
}),
cache: new InMemoryCache()
})
When I add authorizan in headers I got this Error:Response not sucessful:Received status code 500 In React native otherwise it's work perfectly . What is issue here?
Can you try then function for async function
getToken().then((token) => {
const client = new ApolloClient({
link: createUploadLink({
uri: 'http://192.168.1.82:8080/graphql',
headers: {
authorization: token
}
}),
cache: new InMemoryCache()
});
});

react native iOS Apollo - TypeError: Network request failed - URI accessible from outside the app

I've got a graphql URI that I need to query from my react-native App. This URI is public and I've got access to its schema/structure when I simply type the URI in my browser.
As soon as I try to query it from my code, I get the [TypeError: Network request failed] error (logs are created in the function that builds my ApolloClient).
I've checked the URI a million time, it's the same as the one I put in my browser, and the one I've used in the past to successfully query the DB.
This is the client-building function:
export function initServices({
uri,
authToken,
mockMeanDelay = 400,
mock = false,
mockScenarios = [],
}: Options): Services {
let mockRemoteController = null;
let linkToOutsideWorld: ApolloLink;
const messageBus = createMessageBus();
const terminatingLink = createUploadLink({
uri: CORRECT_URI_HERE,
})
const authLink = setContext(async (_, { headers }) => {
const token = await authToken();
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
linkToOutsideWorld = from([authLink, withCustomScalars(), terminatingLink]);
const errorReportingLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
// eslint-disable-next-line no-console
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
// eslint-disable-next-line no-console
if (networkError) console.error(`[Network error]: ${networkError}`);
});
const link = ApolloLink.from([errorReportingLink, linkToOutsideWorld]);
const fragmentMatcher = new IntrospectionFragmentMatcher({
// #ts-ignore
introspectionQueryResultData: introspectionResult,
});
const apolloClient = new ApolloClient({
link,
defaultOptions: {
watchQuery: {
// We prefer using a `cache-and-network` policy so that screens
// are always in sync with backend
// Otherwise, the default policy would not fetch the server
// data from server if the result of query is already in cache
fetchPolicy: 'cache-and-network',
},
},
cache: new InMemoryCache({
cacheRedirects: {
Query: {
// #ts-ignore issue in typing of cacheRedirects
userById: (_, { userId }: QueryUserByIdArgs, { getCacheKey }) =>
getCacheKey({ __typename: 'User', id: userId }),
// #ts-ignore issue in typing of cacheRedirects
gatheringSpaceById: (
_,
{ gatheringSpaceId }: QueryGatheringSpaceByIdArgs,
{ getCacheKey },
) =>
getCacheKey({
__typename: 'GatheringSpace',
id: gatheringSpaceId,
}),
// #ts-ignore issue in typing of cacheRedirects
gatheringInstanceById: (
_,
{ gatheringInstanceId }: QueryGatheringInstanceByIdArgs,
{ getCacheKey },
) =>
getCacheKey({
__typename: 'GatheringInstance',
id: gatheringInstanceId,
}),
},
},
fragmentMatcher,
}),
});
return { apolloClient, messageBus, mockRemoteController };
}
When I replace the URI with another publicly available one, it seems to work so my guess is that there's an issue with the back-end side. But how is it possible that I have full access to the schema and queries with my browser?
Any tips to help debugging are welcome too!
Thanks for your help!

Next.js: React Apollo Client Not sending cookies?

I'm using Apollo Client as a graphql client on my next.js application, Here is the function that creates a client for me:
let client: ApolloClient<any>;
export const __ssrMode__: boolean = typeof window === "undefined";
export const uri: string = "http://localhost:3001/graphql";
const createApolloClient = (): ApolloClient<any> => {
return new ApolloClient({
credentials: "include",
ssrMode: __ssrMode__,
link: createHttpLink({
uri,
credentials: "include",
}),
cache: new InMemoryCache(),
});
};
Surprisingly, when I make a mutation to the graphql server I'm able to set the cookies but, I'm not able to get the cookies from the client. What may be possibily the problem?
I came to the same problem, my solution was to create a client every time a server-side rendering is made, maybe it's not ideal to have a client to execute GraphQL calls in the browser and others in the server but it's what worked best for me. This is the code:
import { ApolloClient, createHttpLink, InMemoryCache } from '#apollo/client';
import { NextPageContext } from 'next';
import { setContext } from '#apollo/client/link/context';
export const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include',
});
const CreateClient = (ctx: NextPageContext | null) => {
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
cookie:
(typeof window === 'undefined'
? ctx?.req?.headers.cookie || undefined
: undefined) || '',
},
};
});
return new ApolloClient({
credentials: 'include',
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
ssrMode: true,
});
};
export default CreateClient;
So, what I do is pass the context from the getServerSideProps and see if I have some cookies there, if so I just set the cookies, you can also send the authorization token if it's in the cookie. To call it is very simple:
export async function getServerSideProps(context: NextPageContext) {
const client = CreateClient(context);
const { data } = await client.query({
query: SOME_QUERY,
});
return {
props: {
data,
},
};
}
You can also do a HOC as in the Ben Awad tutorial Apollo Client HOC but I think it was too much for what I was trying to do. Hope it helped you or helps someone there :)
Also, I'm using Next 12.1.5 and React 18

Tipsi-Stripe creating a source from a token

I am trying to use tipsi-stripe to create a source which I will send to my server. I get the token fine with following code but creating a source from the token
throws an error
try {
this.setState({ loading: true, token: null })
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: 'full',
prefilledInformation: {
billingAddress: billingAddress,
},
})
this.setState({ 'token': token })
var strToken=this.state.token;
console.log(strToken);
const params = {
type:'card',
token:strToken
}
const source = await stripe.createSourceWithParams(params)
Error is as follows
[Error: The payment method `card` requires the parameter: card[number].]
What am I doing wrong?

How to pass Additional Header when calling mutation in React native apollo client?

How to pass Additional Header when calling mutation in React native apollo client ?
my Client is here:
import { HttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
const makeApolloClient = (token) => {
// create an apollo link instance, a network interface for apollo client
const link = new HttpLink({
uri: 'http://x.x.x.x:xxxx/xxxx',
headers: {
Authorization: `Bearer ${token}`
},
});
// create an inmemory cache instance for caching graphql data
const cache = new InMemoryCache();
// instantiate apollo client with apollo link instance and cache instance
const client = new ApolloClient({
link,
cache
});
return client;
};
export default makeApolloClient;
If i need to add additional header to this same client when using query or mutation how can i do it ?
Is it possible with "apollo-link-context" ?
You haven't specified your React version however assuming you use Hooks you do it as follows. If you aren’t using hooks change the doc version for the links at the bottom of this answer using the drop down in the top left.
Where you have your query:
const GET_USER = gql`
query getUser{
node {
name
age
}
}
`;
You’ll want to run a query with the useQuery hook:
const { loading, error, data } = useQuery(GET_USER, {
context: {
headers: {
"Content-Type": "application/json"
}
}
})
Docs:
You can find the docs for each here:
- UseQuery: https://www.apollographql.com/docs/react/essentials/queries/
- Context Headers: https://www.apollographql.com/docs/link/links/http/#passing-context-per-query
This can be done by receiving the context which is set in mutation/query.
Setting Custom header in mutation
const [addTodo] = useMutation(ADD_TODO, {
refetchQueries: [{ query: GET_TODO }], //updating the list of todos list after adding
context: {
headers: {
"x-custom-component-add": "kkk-add",
"x-origin-server": "pure-react"
}
}
});
receiving context in middle ware which set in mutation/query
const httpLink = new HttpLink({ uri: "https://sxewr.sse.codesandbox.io/" });
const authMiddleware = new ApolloLink((operation, forward) => {
const customHeaders = operation.getContext().hasOwnProperty("headers") ? operation.getContext().headers : {};
console.log(customHeaders);
operation.setContext({
headers: {
...customHeaders
//we can also set the authorization header
// authorization: localStorage.getItem('jjjjjj'),
}
});
return forward(operation);
});
Finally passing the middleware in Apoolo Client
const client = new ApolloClient({
cache: new InMemoryCache(),
link: from([authMiddleware, httpLink])
});
Here is the working sample.
https://codesandbox.io/s/passing-custom-header-in-graphql-mutation-query-l332g?file=/src/index.js
Custom header look like this