Search code examples
javascriptreactjsrestgraphqlgatsby

How can I use axios for fetching data in gatsby useStaticQuery?


I can use graphql for fetching data in gatsby like this :

import { graphql, useStaticQuery } from "gatsby"

const IndexPage = () => {

  const gatsbyRepoData = useStaticQuery(graphql`
    {
      github {
        repository(name: "gatsby", owner: "gatsbyjs") {
          id
          nameWithOwner
          url
        }
      }
    }
  `)

How can I use axios to fetch a rest api with useStaticQuery lifecycle in gatsby js ?


Solution

  • No, you can't. The purpose of useStaticQuery is to get static data (hence the name) from your project, your metadata, or, depending on your data structure, your own project files.

    To get dynamic data from outer sources you need to use a gatsby-node.js file.

    Check: