I am currently having issues with Graphql mutation. Hard coding updating elements works but option 2 where I pass in argument does not.
On Google Dev Tools Network, I see I am passing [object Object] as request for elements.
I tried changing to code below which resulted in type any error and duplicate identifier args error.
`{args.elements}`
Any tips appreciated.
Also, I am not using variables as the api does not seem to accept them??
api.ts OPTION 1: WORKS
export const mutateReq = (args: TW): AxiosPromise<TW[]> => {
const query = `
mutation {
update ( id:"${args.id}", name:"${args.name}", iconFile:"${args.iconFile}", elements:[
[
{id:"2",name:"element2",link:"https:",elements:[{id:"1",name:"element1",link:"https://",elements:[]}]}
],
[
{id:"3",name:"element3",link:"https://",elements:[{id:"4", name: "wr", link: "http://", elements: []}]}
],
[]
]){
id
name
iconFile
elements {
id name link
elements {
id name link
}
}
}
}`;
return axios({
url: url,
method: 'post',
headers: {
'Content-Type': 'application/json',
},
data: {
query: query,
},
});
};
api.ts OPTION 2: DOES NOT WORK
export const mutateReq = (args: TWorkSpace): AxiosPromise<TWorkSpace[]> => {
const query = `
mutation {
update ( id:"${args.id}" name:"${args.name}" iconFile:"${args.iconFile}" elements:${args.elements}){
id
name
iconFile
elements {
id name link
elements {
id name link
}
}
}
}`;
return axios({
url: url,
method: 'post',
headers: {
'Content-Type': 'application/json',
},
data: {
query: query,
},
});
};
args data type
{
id: "1" name: "1" iconFile: "icon.png"
elements: [
[
{id:"2",name:"element2",link:"https://",elements:[{id:"1",name:"element1",link:"https://",elements:[]}]}
],
[
{id:"3",name:"element3",link:"https://",elements:[{id:"4", name: "wr", link: "http:", elements: []}]}
],
[]
]
}
Your GQL query is a string and when you try elements:${args.elements} it will try to convert the object to a string which will most likely liik like [object Object], but what you need to do is convert it to a JSON string which will give you the output you are looking for.
Try:
elements:${JSON.stringify(args.elements)}
Related
i am destructuring an array to create html elements based on the data but i am finding a hard time figuring out how to remove the ',' after destructuring...
const elements = data.map((links) => {
const keys = Object.keys(links);
return `<div class="links"><p class="${keys[0]}">${links.website}</p>
${links.userName}</div>`;
});
result:
<div class="links"><p class="website">Linkedin</p>
André Silveira</div> **,**
the ',' is appearing on the DOM, how do i remove it ?
I tried to destructuring it to a string but then i am not being able to create elements based on criteria.
Here is the data:
export const data = [
{
website: "Linkedin",
url: "https://www.linkedin.com/in/andresilveira717",
userName: "André Silveira"
},
{
website: "Github",
url: "https://github.com/the717q",
userName: "#the717q"
},
{
website: "Twitter",
url: "https://twitter.com/the717q",
userName: "#the717q"
}
];
When you are attempting to insert a HTML string into the DOM, ensure it is not an array of strings instead of a string. Otherwise you will see commas in the output (most likely due to Array.prototype.toString() being implicitly called on the array).
You can use elements.join('') to get a html string of all the elements without commas in between them.
const data = [
{
website: "Linkedin",
url: "https://www.linkedin.com/in/andresilveira717",
userName: "André Silveira"
},
{
website: "Github",
url: "https://github.com/the717q",
userName: "#the717q"
},
{
website: "Twitter",
url: "https://twitter.com/the717q",
userName: "#the717q"
}
];
const elements = data.map((links) => {
const keys = Object.keys(links);
return `<div class="links"><p class="${keys[0]}">${links.website}</p>
${links.userName}</div>`;
});
document.querySelector('#root').insertAdjacentHTML('beforeEnd', elements.join(''))
<div id="root"></div>
I'm using Strapi as a CMS, where I query for slugs, and I would like to have statically generated pages using getStaticPaths and getStaticProps in Next.js.
As I need to work with multiple locales, I have to map through the locales and get paths for each "Announcements" I'm getting from my query.
The error message I'm getting is:
Error: A required parameter (slug) was not provided as a string in getStaticPaths for /updates/announcements/[slug]
This is my getStaticPaths:
export async function getStaticPaths({ locales }: any) {
const paths = await (
await Promise.all(
locales.map(async (locale: any) => {
const { data } = await client.query({
query: gql`
query Announcements {
announcements(locale: "${locale}") {
data {
attributes {
slug
locale
}
}
}
}
`,
});
return {
announcements: data.announcements.data,
locale,
};
})
)
).reduce((acc, item) => {
item.announcements.map((p: any) => {
acc.push({
params: {
slug:
p.attributes.slug === "/" ? false : p.attributes.slug.split("/"),
},
locale: p.attributes.locale,
});
return p;
});
return acc;
}, []);
return {
paths,
fallback: false,
};
}
If I console.log(paths) I get the following in the terminal:
[
{ params: { slug: [Array] }, locale: 'en' },
{ params: { slug: [Array] }, locale: 'en' },
{ params: { slug: [Array] }, locale: 'en' },
{ params: { slug: [Array] }, locale: 'da' },
{ params: { slug: [Array] }, locale: 'sv' },
{ params: { slug: [Array] }, locale: 'nb' }
]
I might think that Next.js don't want the slug to be an array, but I'm not entirely sure. What am I doing wrong?
You page uses dynamic routes named (/updates/announcements/[slug]), therefore the param slug is required in paths.
From the Next.js getStaticPaths documentation:
The paths key determines which paths will be pre-rendered. For example, suppose that you have a page that uses Dynamic Routes named pages/posts/[id].js. If you export getStaticPaths from this page and return the following for paths:
return {
paths: [
{ params: { id: '1' }},
{
params: { id: '2' },
// with i18n configured the locale for the path can be returned as well
locale: "en",
},
],
fallback: ...
}
Then, Next.js will statically generate /posts/1 and /posts/2 during next build using the page component in pages/posts/[id].js.
The slug param can only be a string since it's used to generate routes. As you found when logging paths, you were trying to pass slug: [Array].
The problem in the question's code snippet is this expression to assign a slug:
// ...
params: {
slug: p.attributes.slug === "/" ? false : p.attributes.slug.split("/"), // 👈
},
// ...
This expression will either assign false (boolean) or an array of substrings (see the docs for String.prototype.split()).
In this case, as confirmed in a comment above, simply passing the slug as a string solves the issue.
The confusion likely came from following a tutorial that uses an optional catch-all route (pages/[[...slug]]) instead of regular dynamic routes (pages/[slug]) (ref).
From the Next.js getStaticPaths documentation again:
If the page name is pages/posts/[postId]/[commentId], then params should contain postId and commentId.
If the page name uses catch-all routes like pages/[...slug], then params should contain slug (which is an array). If this array is ['hello', 'world'], then Next.js will statically generate the page at /hello/world.
If the page uses an optional catch-all route, use null, [], undefined or false to render the root-most route. For example, if you supply slug: false for pages/[[...slug]], Next.js will statically generate the page /.
When I'm adding docs to elasticsearch with _id set I get:
Field [_id] is a metadata field and cannot be added inside a document. Use the index API request parameters.
Using client.bulk
const body = dataset.flatMap(doc => [{ index: { _index: 'myindex' } }, doc])
const { body: bulkResponse } = await client.bulk({ refresh: true, body })
I don't see a place to put the _id in the parameters.
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html
Am I supposed to use a different method?
Thanks.
It needs to be inside the command part, but you also need to remove it from the source document in doc:
here
|
v
const body = dataset.flatMap(doc => [{ index: { _index: 'myindex', _id: doc._id } }, doc])
const { body: bulkResponse } = await client.bulk({ refresh: true, body })
I have been trying to filter the results of an API call based on my "note" value. I've been building it on Zapier and the call works but I cannot seem to find a way to make a filter function do its job (so if I replace line 19-23 with return results; then it gives me all orders from the api call). I've poured over every stack document I could find but they all end with the error result.filter not found, or a bargle error (generic error in Zapier).
const options = {
url: `https://mystorename.myshopify.com/admin/orders.json?`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
var results = z.JSON.parse(response.content);
var queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem);
return filteredOrders;
});
And this is an example of my current output with return results; and no filter:
{
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
Again the goal is to filter by the value in the "note" key. So if my filter input is 555-5555 then it should return all information for that item only. I did try to use an if statement for return, stringify instead of parse, covert to array...all with needed code, but regardless of the format I find filter does not work or nothing is returned. Going to keep working on it, so if I happen to find the answer I will post that, but at this point I feel stuck.
You are trying to use the method filter in a object but filter is only available in an array so you should try to call filter in the orders array.
let results = {
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
let queryItem = "555-5555";
let newArray = results.orders.filter(function (item) {
return item.note == queryItem
})
console.log(newArray)
Updated to contain a real http call:
const url = 'http://www.mocky.io/v2/5d9466142f000058008ff6b7'
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
const response = await fetch(url, options)
const results = await response.json()
const queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem)
console.log(filteredOrders)
You are trying to filter on results, but according to your output, you should be filtering on results.orders.
const filteredOrders = results.orders.filter(item => item.note === queryItem);
Are you getting all the orders back (all the orders with the specified filter value)?
I realized I wasn't getting back all orders and this did the trick:
`https://mystorename.myshopify.com/admin/orders.json?status=any`
Alternatively, you can query the orders with that specific note:
`https://mystorename.myshopify.com/admin/orders.json?status=any¬e=` + queryItem
I have a server side schema with this mutation type
type Mutation {
updateSettings(settings: SettingsInput): Settings
}
input SettingsInput {
repositories: [RepositoryInput]
}
input RepositoryInput {
id: String
name: String
url: String
}
I can mutate this exactly like I want to if I use a client such as Altair, with this query:
mutation{
updateSettings(settings: {
repositories: [
{
name: "name1"
url: "url1"
},
{
name: "name2"
url: "url2"
}
]
}){
repositories {
id
name
url
}
}
}
However I am struggling to get it working when using Apollo
The best I can get is this
import { SubscriptionClient } from "subscriptions-transport-ws";
import { gql } from "apollo-boost";
import { WebSocketLink } from "apollo-link-ws";
const wsClient = new SubscriptionClient("ws://localhost:5001/graphql", {
reconnect: true
});
const client = new WebSocketLink(wsClient);
const UPDATE_SETTINGS = gql`
mutation UpdateSettings($settings: SettingsInput) {
updateSettings(settings: $settings) {
repositories {
id
name
url
}
}
}
`;
client
.request({
query: UPDATE_SETTINGS,
variables: { repository: [{name: "name1", url:"url1"},
{name: "name2", url:"url2"}]}
})
I am obviously missing something. The client doesn't seem to be aware of the servers SettingsInput, but I can't really figure out how to create a query for the client that takes complex objects or arrays as variables.
Am I going about this in a totaly weird way or how do I go about sending "complex" mutations to the server from an apollo client?
The client aside, you also need to fix the variables object you're passing in. The variable you've defined in your operation is named settings, but you are only passing in a variable named repository. Additionally, the shape of this variable doesn't match SettingsInput as shown in your schema. variables should look something like:
const variables = {
settings: {
repositories: [
{
name: 'name1',
url: 'url1'
},
{
name: 'name2',
url: 'url2'
},
],
},
}