Gatsby: Resolving the issue where tslint requires a component to receive props directly from the query within the component

Utilizing Gatsby along with Typescript, I have been working on developing a blog that is powered by Contentful CMS.

In the process, I have created a FeaturedPost component that I intend to showcase on the main page, and here is the implementation:

FeaturedPost.tsx

interface IProps {
  data: {
    contentfulPost: ContentfulPost;
  };
}

const FeaturedPost: React.FunctionComponent<IProps> = ({ data }) => {
  const { title, description } = data.contentfulPost;
  return (
    <>
      <Header>{title}</Header>;
      <div>{description}</div>
    </>
  );
};

export const query = graphql`
  query featuredPost($slug: String) {
    contentfulPost(slug: { eq: $slug }) {
      title
      slug
      description {
        childMarkdownRemark {
          html
        }
      }
    }
  }
`;

export default FeaturedPost;

This snippet displays my index page code:

index.tsx

const IndexPage: React.FunctionComponent<P> = () => {
  return (
    <Layout>
      <SEO
        title="Home"
        keywords={[`gatsby`, `application`, `react`]}
        description="Index for something I can't remember?!"
      />
      <FeaturedPost />
      <h1>Hi people</h1>
      <p>Welcome to your new Gatsby site.</p>
      <p>Now go build something great.</p>
      <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }} />
    </Layout>
  );
};

export default IndexPage;

Tslint is currently expecting me to pass a prop named data to the FeaturedPost component due to the implementation of interface IProps, even though there is no actual data being passed.

The FeaturedPost component retrieves this data as a response from the query it sends. Any suggestions on what might be causing this issue or how I could address it to satisfy the linter?

Answer №1

If you are using Gatsby v2, be aware that graphql queries in non-page components will no longer work as expected. Instead, consider using StaticQuery as an alternative. Below is a simple example:

import * as React from 'react'
import { StaticQuery, graphql, Link } from 'gatsby'

type TOCDataType = {
  readonly allSitePage: {
    edges: [
      {
        node: {
          id: string
          path: string
        }
      }
    ]
  }
}

const TableOfContents: React.FunctionComponent<{}> = () => (
  <StaticQuery
    query={graphql`
      query SitePageQuery {
        allSitePage {
          edges {
            node {
              id
              path
            }
          }
        }
      }
    `}
    render={(data: TOCDataType) => (
      <div>
        {data.allSitePage.edges.map(({ node }) => (
          <li key={node.id}>
            <Link to={node.path}>{node.path}</Link>
          </li>
        ))}
      </div>
    )}
  />
)

export default TableOfContents

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding intricate SVG components onto a chosen group

My current project involves creating an interactive schema that includes complex SVG elements, such as groups containing multiple sub-objects like rect, path, and text. I am wondering if there is a way to store the description of these elements in a varia ...

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

Tips for launching a new page with a button click in React.js without relying on Routers

I am completely new to React and trying to figure out how to dynamically load a new page component within the main page without changing the URL. Essentially, I want to open up a fresh page upon clicking a button on the main page, displaying only the conte ...

How can I use JavaScript to consistently fetch the CSS-defined percentage setting for padding/margin instead of the pixel size?

How can I retrieve the padding set in CSS for a div with {padding:10% 10px 20% 10px;} using JavaScript, considering that window.getComputedStyle(myelement).getPropertyValue('padding'); returns different results? In Firefox, it shows as "10% 10px ...

What prevents me from initializing a blank Map or Set using Object.create?

Unfortunately, the code snippet provided is not functioning as expected. Here's what I attempted: const x = Object.create(Set.prototype) x.has(1) const y = Object.create(Map.prototype) y.get(1) I wanted a method to generate empty objects rega ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...

How to Retrieve Values from Dynamic Arrays in JavaScript Without Specifying Keys

var data = [ { 'Specials 5': 2192, 'dates': '2021-06-14' }, { 'Specials 8': 767, 'dates': '2021-06-16' }, { 'Specials 13': 2264,'dates': '2021-06-18' }, ] ...

Ways to transform a React class-based component into a functional component

I have a code snippet for a React component that implements a carousel slider using a class-based approach. I would like to refactor it into a functional component, but I'm not sure how to do so. import React from "react"; import ...

Disconnection between client and server communications

Can communication between two entities be established in this scenario? For example, if a server receives a file upload and determines it is incorrect, can it send an event to the client? The client would then catch the event and manipulate the DOM to dis ...

ERROR Error: Uncaught (in promise): ContradictionError: The variable this.products is being incorrectly identified as non-iterable, although it

Seeking a way to extract unique values from a JSON array. The data is fetched through the fetch API, which can be iterated through easily. [please note that the product variable contains sample JSON data, I actually populate it by calling GetAllProducts( ...

Exploring the Use of a Spinner in Backbone.js: Best Practices and Timing

Are there any built-in methods in Backbone that allow me to display a spinner whenever data is being fetched from any of the collections, and hide it when the operation is complete? I suspect that implementing this functionality might be more complex than ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

What is the best way to simulate our services for controller testing?

Currently delving into angular js and experimenting with testing a controller. Here is the service I am using: angular.module('test'){ service.getAllServices = function() { var fullPath = url var deferre ...

Using Redis for pub/sub functionality within or outside of the io.connect callback

Is it preferable to move the redis subscription event outside of the io.connect callback if the intention is to broadcast the data to all connected users? Or would it be better to keep it inside the io.connect callback, as shown below: io.on('con ...

Troubleshooting Problems with Owl Carousel Loading

Having trouble with Owl Carousel loading issue. I've set up my carousel using the Owl Carousel jQuery plugin as guided, but it's showing me an "owl-carousel loading" class added to the DOM (owl-loading). I've tried adding custom styles and J ...

XState TypeScript - utilizing the Interprete Service

I have developed a login system using a combination of TypeScript, xState, and React for the UI. The machine I have created includes the following configuration: import { LoginResponse } from 'async/authentication/responseModel'; import Data fro ...

Retrieve mongodb objects that fall within a specified date range

Within my collection, there is an example document structured as follows: { "_id" : ObjectId("5bbb299f06229dddbaab553b"), "phone" : "+38 (031) 231-23-21", "date_call" : "2018-10-08", "adress_delivery" : "1", "quantity_concrete" : "1", ...

I am perplexed by JQuery. It is returning true when comparing an input value from a number type input, and I cannot figure out the reason behind it

Seeking guidance on a perplexing issue. Here is a basic code snippet to depict my dilemma: html: <form> <input type="number" id="someNumber"> <input type="button" id="submitBtn"> </form> jquery: $("#submitBtn"). ...