1

I was given an example for some code that has an array hardcoded. Im looking to swap this out for my array that is pulled in from an API using graphql. Below is the code pen to the original example & another for what i've tried with no avail.

I'm pretty new to graphql & js so likely an amateur mistake, any pointers would be much appreciated!

Original code - https://codesandbox.io/s/nice-saha-gwbwv

My pen - https://codesandbox.io/s/quiet-wind-brq8s?file=/src/App.js

1 Answer 1

1

I would change your component structure to something like:

import React, { useState } from 'react'
import { graphql } from 'gatsby'

 const YourPage = ({data}) => {
   console.log('data is', data)
   const [filters, setFilters] = useState({
    type: "",
    category: ""
  });

//your calculations

  return (
    <div>
      Your stuff 
    </div>
  )
}

export const query = graphql`
  query yourQueryName{
      allStrapiHomes {
        nodes {
          type
          category
        }
      }
  }
`

export default YourPage

In your code, upon some critical imports, you are missing a few stuff from Gatsby. If you use a staticQuery, you will need to add a render mode to it. It may look a bit old-fashioned, it's better to use the useStaticQuery hook provided by Gatsby or adding a page query (my approach).

I've added a page query. Your data is under props.data.allStrapiHomes.nodes, destructuring props you omit the first step, so your data will be at data.allStrapiHomes.nodes. Both type and category will be an array if they are set like this in the Strapi back-end.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your reply! Ive updated my code and managed to get my array displaying in the console log - imgur.com/a/cn4gD7F I'm now getting an error "TypeError: Cannot read property 'nodes' of undefined" any chance you know whats up with it? Ive updated my codepen with the code - codesandbox.io/s/quiet-wind-brq8s?file=/src/App.js
Is the query working in localhost:8000/___graphql? Is data returning a value?
Yeah - imgur.com/a/W34uBhY In the code i had to change 'data' to items to get anything to appear in the console log though
Turns out id renamed data to items elsewhere, oops! thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.