I am building a React-Nextjs application. I am connecting graphql api in my project. I write one request function-
await axios.post(process.env.NEXT_PUBLIC_API_URL as string, {
query: `
query isListed {
isListed(name: ["Thor: Love and Thunder"]) {
name
isWatchlisted
isWishlisted
}
}`
})
.then(res => console.log(res))
.catch(err => console.log(err))
This is working properly. Here You can see that ["Thor: Love and Thunder"]
, I am sending static data. When I try to use dynamic data Then I face the problem. The api documentation says that they only accept array of string.
Here is example when I try to use dynamic data-
const test = ["Thor: Love and Thunder"]
//Here I try to use this test data
await axios.post(process.env.NEXT_PUBLIC_API_URL as string, {
query: `
query isListed {
isListed(name: ${test}) {
name
isWatchlisted
isWishlisted
}
}`
})
.then(res => console.log(res))
.catch(err => console.log(err))
When I try it, it gives me a syntax error. But I can't understand what is the different between this two example. Please help me.
CodePudding user response:
You are interpolating strings. Arrays, when coerced into a string, will be joined with commas, but without brackets. For instance, let a=[1,2,3]; let s=`${a}`;
will give you the string s with value '1,2,3'
.
In your case, you have two options: use a string literal instead of the array, or use JSON.stringify
when interpolating.
So either
const test = '["Thor: Love and Thunder"]'
…
or
…
query: `
query isListed {
isListed(name: ${JSON.stringify(test)}) {
name
isWatchlisted
isWishlisted
}
}`
…
CodePudding user response:
Arrays don't automatically seralize to JSON.
Try using:
await axios.post(process.env.NEXT_PUBLIC_API_URL as string, {
query: `
query isListed {
isListed(name: $name) {
name
isWatchlisted
isWishlisted
}
}
`,
variables: {
name: test,
}