Why does graphql not inject my data into react component prop? - javascript

I am using this tutorial to create a gatsby blog that will use Markdown pages.
I am trying to create a 'post-repeater' component that will loop through all my posts and create links to them using frontmatter that looks like this.
---
path: "/blog/my-first-post"
date: "2019-05-04"
title: "My first blog post"
---
I have a graphQl query that is correctly pulling the data.
My component looks like this.
import React from "react"
import "../styles/post-repeater.scss"
import { graphql, Link } from "gatsby"
export default function PostRepeater({postQuery}){
console.log('my data:',postQuery);
return(
<>
{postQuery.map(instance =>
<div className="post">
<h2>{instance.title}</h2>
<span className="datePosted">{instance.date}</span>
<span className="readTime"></span>
<p></p>
<Link to={instance.path}>Read More</Link>
<hr />
</div>
)}
</>
)
}
export const postQuery = graphql`
query MyQuery {
allMarkdownRemark {
edges {
node {
frontmatter {
path
title
date
}
}
}
}
}
`
If I put a console.log of postQuery from inside the PostRepeater component, it comes back as undefined. So it appears that the component is never getting the data even though I followed the same layout from the tutorial above.
If I put a console.log('data', postQuery); from outside the component, I get the following in the console.
data 2575425095
What am I doing wrong?

After making a query gatsby injects it as an object matching the query.
In your case, as you see in GraphiQL you get an object with the initial key data.
{
"data": {
"allMarkdownRemark": {
"edges": [
{
"node": {
"frontmatter": {
"title": "...",
"date": ...
}
}
}
]
}
}
}
What you tried to do, is destructing a not existing key postQuery.
Moreover, you still can log it outside of the component scope as the value exported from export const postQuery
export const postQuery = graphql`
query MyQuery {
allMarkdownRemark {
edges {
node {
frontmatter {
path
title
date
}
}
}
}
}
`;
// v Logs the query id
console.log('my data:', postQuery);
// v Is not defined
export default function PostRepeater({ data, postQuery }) {
// v Shadowing the outter value of postQuery
console.log('my data:', postQuery);
// The query injected as "data" object
console.log('my data:', data);
return (
<>
// v Be aware of which object you query, edges is an array
{data.allMarkdownRemark.edges.map(...)}
</>
);
}

The export of graphql queries which gets automatically attached to props only work for page components. For any non-page components you need to use either the StaticQuery component or the useStaticQuery hook.
Read more here:
https://www.gatsbyjs.com/docs/static-query/
Here is how your code should look like using the useStaticQuery hook
import React from "react"
import "../styles/post-repeater.scss"
import { graphql, useStaticQuery, Link } from "gatsby"
export default function PostRepeater() {
const data = useStaticQuery(graphql`
query MyQuery {
allMarkdownRemark {
edges {
node {
frontmatter {
path
title
date
}
}
}
}
}
`)
// you might have multiple nodes in which case you must use filter
// or find to get node which contains your data.
const postQuery = data.allMarkdownRemark.edges[0].node.frontmatter;
return (
<>
{postQuery.map(instance =>
<div className="post">
<h2>{instance.title}</h2>
<span className="datePosted">{instance.date}</span>
<span className="readTime"></span>
<p></p>
<Link to={instance.path}>Read More</Link>
<hr />
</div>
)}
</>
)
}

Related

Query values lost on page refresh in Next js? [Example given]

I am making a simple Next Js application which has only two pages..
index.tsx:
import React from "react";
import Link from "next/link";
export default function Index() {
return (
<div>
<Link
href={{
pathname: "/about",
query: { candidateId: 8432 }
}}
as="about"
>
Go to the about page
</Link>
</div>
);
}
As per the above code, on click Go to the about page it goes to about page and using query I also receive the passed query values in about page.
about.tsx
import React from "react";
import Router, { withRouter } from "next/router";
function About({ router: { query } }: any) {
return (
<div>
Candidate Id: <b> {query.candidateId} </b>
</div>
);
}
export default withRouter(About);
This displays the value but on page refresh while we are in /about page, the candidateId received gets disappeared.
Requirement: Kindly help me to retain the query value passed down from one page to another page even on page refresh.
Note: As per my requirement I should not display the canidateId on url while navigating and hence I am using as approach.. I know I can achieve it if I remove as but I cannot remove that here in index page while navigating.. Reason is this will lead to displaying candidateId in the url which is not intended..
Tried this solution: https://stackoverflow.com/a/62974489/7785337 but this gives empty query object on refresh of page.
Stuck for very long time with this please kindly help me.
If you do not want to use the query parameter you may need to create a "store" that saves your variable that persist throughout your pages.
Sample code as follows.
//candidatestore.js
export const CandidateStoreContext = createContext()
export const useCandidateStore = () => {
const context = useContext(CandidateStoreContext)
if (!context) {
throw new Error(`useStore must be used within a CandidateStoreContext`)
}
return context
}
export const CandidateStoreProvider = ({ children }) => {
const [candidateId, setCandidateId] = useState(null);
return (
<CandidateStoreContext.Provider value={{ candidateId, setCandidateId }}>
{children}
</CandidateStoreContext.Provider >
)
}
Then you need to wrap the Provider around your app like
<CandidateStoreProvider><App /></CandidateStoreProvider>
This way you can use anywhere as follows both in your index page and your about page.
const { candidateId, setCandidateId } = useCandidateStore()
UseContext
In your codes, it should probably look something like that.
import React from "react";
import Link from "next/link";
import { useCandidateStore } from './candidatestore'
export default function Index() {
const { candidateId, setCandidateId } = useCandidateStore()
useEffect(() => {
setCandidateId(thecandidateId)
})
return (
<div>
<Link
href={{
pathname: "/about",
}}
as="about"
>
Go to the about page
</Link>
</div>
);
}
function About({ router: { query } }: any) {
const { candidateId, setCandidateId } = useCandidateStore()
return (
<div>
Candidate Id: <b> {candidateId} </b>
</div>
);
}
Update to Next.JS 10. It comes with Automatic Resolving of href which fixes your problem.
Try to delete the as="about" and then navigate again to the "about" page, the issue should be gone.
Codesandbox
My best bet would be to store the candidateId in an encrypted session on the client side. You could read/verify cookies in getServerSideProps() and pass their contents to the page component. If this sounds feasible, I'd recommend checking out the next-iron-session.
Another approach would be to check if candidateId exists in the query object in getServerSideProps(). If it does then pass it straight to the page component. If not, either get it elsewhere, redirect, or pass some default value. Append the following starter code to your about.tsx:
/* ... */
export function getServerSideProps({ query }: any) {
// if query object was received, return it as a router prop:
if (query.candidateId) {
return { props: { router: { query } } };
}
// obtain candidateId elsewhere, redirect or fallback to some default value:
/* ... */
return { props: { router: { query: { candidateId: 8432 } } } };
}
index.tsx file
Keep the code same as it is.
import React from "react";
import Link from "next/link";
export default function Index() {
return (
<div>
<Link
href={{
pathname: "/about",
query: { candidateId: 8432 }
}}
as="about"
>
Go to the about page
</Link>
</div>
);
}
AboutUs.tsx
Code starts from here
Adding router as a dependency in the useEffect the issue should get solved.
import Router, { useRouter } from "next/router";
import React, { useState, useEffect } from 'react';
function About({ router: { query } }: any) {
const route = userRouter();
const [candidateId, setCandidateid] = useState();
useEffect(() => {
const {candidateId} = router.query
if(candidateId) {
setCandidateid(candidateid)
}},[router]) //Here goes the dependency
return (
<div>
Candidate Id: <b> {candidateId} </b>
</div>
);
}
export default (About);

How can I use a field as a filter from one graphql query to get a fluid image thats in a separate query?

I have two graphql sources, one for fluid images and one for characters in a mongo database. I'm mapping the characters to the page and I need to use the character names (the name field in the "allMongodbMobileLegendsdevChamps") as a filter (using originalName filter possibly) to find the fluid img. So I have something like this
query MyQuery {
allMongodbMobileLegendsdevChamps {
nodes {
name
}
}
allImageSharp(filter: {fluid: {originalName: {eq: "characterName.jpg"}}}) {
nodes {
fluid {
...allImageSharpFluid
}
}
}
}
const Index = ({ data }) => {
const {
allMongodbMobileLegendsdevChamps: { nodes: champs },
allImageSharp: { nodes: fluid },
} = data
return (
<section className={grid}>
{champs.map(champ => {
return (
<Link to={`/champ/${champ.name}`}>
<Image fluid={fluid.fluid} />
<h3>{champ.name}</h3>
</Link>
)
})}
</section>
)
}
If I wasnt using graphql, I'd just set the src in image to "champ.name" like this:
<Image src = `/path/to/img/${champ.name}.jpg` />
How can I filter my image query with the champ.name? Should I use Apollo for something like this?
This is Gatsby and currently it is not possible because you can’t pass in variables to queries follow this GH issue https://github.com/gatsbyjs/gatsby/issues/10482
Supposing that passing variables was possible, I would make all characters as a page query that will allow me to restructure the name from props and then a static query to which I would pass in the name as filter.
I used this solution and adapted it slightly for my needs: Variables in graphQL queries
In a parent component I map all the champions and create a child component for each one, and pass it the champions name.
In the child component, I have a variable, name, that stores the correct node for the image I want to display by using the find method to match the champions name to the images relativePath (the images have the same exact name as the champion). I then call the function renderImage which consumes the variable "name" and finds the fluid image in node.childImageSharp.fluid, and creates my image component with the correct fluid image location.
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import { displayName } from "../../utils/championName"
import * as S from "../styled/ChampionGridCard"
const renderImage = file => {
return <S.ChampionImage fluid={file.node.childImageSharp.fluid} />
}
const ChampionGridCard = props => {
const data = useStaticQuery(graphql`
{
allFile(filter: { sourceInstanceName: { eq: "champImages" } }) {
edges {
node {
extension
relativePath
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`)
const name = data.allFile.edges.find(
image => image.node.relativePath === `ssbu/${props.champName}.jpg`
)
return (
<S.ChampionGridCard to={`/champ/${props.champName}`}>
<S.ChampionImageWrapper>{renderImage(name)}</S.ChampionImageWrapper>
</S.ChampionGridCard>
)
}
export default ChampionGridCard

Data from Gatsby GraphQL always returns undefined?

Gatsby noob here so please bear with me. I have a component that accepts props from the index.js where it is supposed to receive data from an array of objects but will always receive the error TypeError: Cannot read property 'map' of undefined where it's referring to the Hero.js component index.js is calling for.
My assumption is that the data being queried in index.js is either not specific enough or that it is rendering the component before data is received. Here is the index.js file:
import { graphql } from 'gatsby';
import { Layout, SEO, Hero } from 'components';
const IndexPage = ({ data }) => {
const dataFetch = data.contentfulTemplateIndex.heroes;
let tester = () => {
for (let count = 0; count < dataFetch.length; count++) {
return <Hero {...props} />;
}
};
console.log(dataFetch);
let props = {
impactText: dataFetch.impactText,
labels: dataFetch.labels,
primaryLabel: dataFetch.primaryLabel,
location: dataFetch.location
// supportingText: dataFetch.supportingText.json
};
return (
<Layout>
{dataFetch && tester()}
</Layout>
);
};
export const query = graphql`
query {
contentfulTemplateIndex {
heroes {
image {
fluid {
src
}
}
impactText
labels
location
primaryLabel
supportingText {
json
}
}
}
}
`;
export default IndexPage;
Here is the Hero.js component which index.js is calling:
import { Link } from 'gatsby';
import { documentToReactComponents } from '#contentful/rich-text-react-renderer';
import cx from 'classnames';
import styles from './hero.module.scss';
const Hero = (props) => {
return (
<div>
<ul>
<Link className={styles.pills}>{props.primaryLabel}</Link>
{props.labels.map((label) => {
return <Link className={styles.pills}>{label}</Link>;
})}
</ul>
<div className={styles.grid}>
<h1>{props.impactText}</h1>
</div>
</div>
);
};
export default Hero;
It's impossible for an outsider to debug your code without a minimum reproducable example.
The best way to debug GraphQL is to use the GraphiQL interface of your browser.
Run gatsby develop. If it fails because of the TypeError remove the lines of code that cause the type error (but not the code of your GraphQL query!). You need to get your development server runnning.
Open your browser, use the URL: http://localhost:8000/___graphql
Copy your graphQL query from your code and paste it into the GraphiQL query window.
Can you access your data there? If not you made a mistake writing your query or the data is not where it's supposed to be.
This way you can make sure the data exists.
It also helps to console.log(props) so you can examine the data object:
const Hero = (props) => {
console.log(props);
return (

Gatsby query works in graphql editor but not in react code

I am working on a blog using Gatsby and I am trying to generate pages based on that tag a user clicks on.
When a user clicks on a tag, he should be redirected to a page that displays a list of articles with that tag.
I created a query that does that. However, my GraphQL query works in my GraphQL editor but not in my react code. It returns an empty array in the code but the expected result when I run the query in the Graphql editor.
import React from "react"
import ArticleCard from "../articleCard/ArticleCard"
import Pagination from "../pagination/Pagination"
import articlesStyles from "./Articles.module.scss"
import { useStaticQuery, graphql } from "gatsby"
const Articles = ({ pageTitle }) => {
const blogPosts = useStaticQuery(graphql`
query($tag: String) {
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___publish_date] },
filter: { frontmatter: { tags: { in: [$tag] } } }
) {
nodes {
frontmatter {
title
publish_date
imageUrl
author
category
}
fields {
slug
}
excerpt(pruneLength: 100)
}
}
}
`)
const nodes = blogPosts.allMarkdownRemark.nodes;
console.log(nodes)
return (
<div className={articlesStyles.contentArea}>
<h1 className={articlesStyles.headerTitle}>{pageTitle}</h1>
<div className={articlesStyles.articles}>
{nodes.map(node => {
return (
<ArticleCard
key={node.id}
{...node.frontmatter}
excerpt={node.excerpt}
slug={node.fields.slug}
/>
)
})}
</div>
<Pagination />
</div>
)
}
export default Articles
As mentioned in the comments, you can't use variables in a staticQuery.
However, this may change in the future as many people stumble upon this limitation and there is work in progress to provide 'dynamicQueries'.
In the meanwhile you can use variables in queries in gatsby-node.js and the templates used by the createPage API. So, in your case, you could generate all the pages for all the tags in gatsby-node.js and still use the same article.js as component template.
See: https://www.gatsbyjs.org/docs/adding-tags-and-categories-to-blog-posts/
As #xadm and #ksav noted in their comments:
"Known Limitations useStaticQuery does not accept variables"
Here as a workaround
Query for all blogs, then use Array.prototype.filter() to get the one you need:
// ...
const blogPosts = useStaticQuery(graphql`
query {
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___publish_date] }
// you can't filter here
) {
nodes {
frontmatter {
title
publish_date
imageUrl
author
category
}
fields {
slug
}
excerpt(pruneLength: 100)
}
}
}
`)
// Get all blogs
const { blogPosts: { allMarkdownRemark: { edges } } } = props;
// filter the blogs
const yourFilteredTag = edges.filter(
el => el.node.childMarkdownRemark.frontmatter.tag === yourTagVariable);
// Now you can get the filtered list of blogs
console.log(yourFilteredTag);
// ...
Edit
As #Albert Skibinski mentioned this solution is not scalable. The context in gatsby-node.js might be a better solution in your use case.
The Array.prototype.filter() solution I described should be reserved for components where the context variable is not available and you can make sure that the size of the array does not grow excedeedingly large.

GraphQL + Relay modern fragment gives me an array of null posts

Im developing a React Native app using Relay modern, GraphQL, and Graphcool. I'm trying to fetch the posts from the DB, and I have 3 files, Post.js, PostList, and the index.js.
PostList.js:
export default createFragmentContainer(PostList, graphql`
fragment PostList_viewer on Viewer {
allPosts(last: 100, orderBy: createdAt_ASC) #connection(key: "PostList_allPosts", filters: []) {
edges {
node {
...Post_post
}
}
}
}
`)
Post.js
export default createFragmentContainer(Post, graphql`
fragment Post_post on Post {
id
content
createdAt
author {
id
username
}
}
`)
index.js
const Feed = () => (
<QueryRenderer
environment={environment }
query={AllPostQuery}
render={({ error, props }) => {
if (error) {
return <div>{error.message}</div>
} else if (props) {
return <PostList viewer={props.viewer} />
}
return <Text>Loading</Text>
}}
/>
)
When I console log this.props.viewer.allPosts inside PostList.js I get { edges: [ null, null, null ], .... I have 3 posts in the DB so it's finding the posts, but why are they null? Pl
first of all if you run into problems try to log the "root" object which is props not a branch inside of it - this will make easier for you to undestrand data structure.
Also, as far as I know Relay does some magic which makes data available for you only in files where you defined a fragment, so in PostList.js you will not see details of the post. Try printing data from Post.js. That's possibly the reason why you see null values printed.
Also data from GraphQL be will be available for you under variable name derived from fragment name after _ (underscore), so in your example it will be post not allPosts.

Categories