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
Advertisement
Answer
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.