I get an error (TypeError: keywords.join is not a function) on below code of Gatsbyjs project, inside seo.js file
.concat(
keywords.length > 0
? {
name: `keywords`,
content: keywords.join(`, `),
} : []
)
I get an error (TypeError: keywords.join is not a function) on below code of Gatsbyjs project, inside seo.js file
.concat(
keywords.length > 0
? {
name: `keywords`,
content: keywords.join(`, `),
} : []
)
You can only apply join
to an array, so keywords
would appear to not be an array at the time join
is called. You need to find out what the value is at that point, so either console.log or adding a breakpoint at that point
Thanks @DanCouper for your response. Currently each post has only one keyword so I removed the join
function and its working fine now. But If in future I plan to have multiple keywords for post then I can use join function but how do I set condition so it doesn’t throw error if there are no multiple keywords for any post.
If keywords
is sometimes an array and sometimes a string, then I suggest you clean that up so that it’s always one or the other.
If you can guarantee that it will be an array, then you can safely use join
without checking via Array.isArray(keywords)
etc.
Even in cases where you’d only have one or no keywords in the array, the join solution works quite cleanly in my opinion.
[].join(', ') // '' empty string
['dog'].join(', ') // 'dog' with no delimiters
['dog', 'cat'].join(', ') // 'dog, cat' with delimiters
But as @DanCouper said, you’re getting that error because whatever keywords
is at runtime is not an Array (or more precisely, doesn’t have a method called join
).
Thanks @colinthornton for the justification. Yes its not an Array its just a string.