Typescript encountered an error indicating that the property "x" is nonexistent on the specified type of 'Readonly<Props> & Readonly<{ children?: ReactNode; }>'

I recently started using Typescript with Nextjs and encountered an error while trying to typecheck a basic component. How can I resolve the error and typecheck my array of objects?

ERROR in C:/Users/Matt/sites/shell/pages/index.tsx(22,4):
22:4 Property 'swc' does not exist on type 'Readonly<Props> & Readonly<{ children?: ReactNode; }>'.
    20 |        render() {
    21 |                const {
    22 |                        swc: { results }
       |                        ^
    23 |                } = this.props;

type Props = {
    results: Array<any>;
};

Component:

interface Props {
    swc: Object;
    results: Array<any>;
}
class swc extends React.Component<Props, {}> {
    static async getInitialProps() {
        const res = await fetch("https://swapi.co/api/people/");
        const swc = await res.json();

        return {
            swc
        };
    }

    render() {
        const {
            swc: { results }
        } = this.props;

        return results.map(swc => (
            <Layout>
    ...
            </Layout>
        ));
    }
}

export default swc;

this.props:

 { swc:
   { count: 87,
     next: 'https://swapi.co/api/people/?page=2',
     previous: null,
     results:
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ] },
  url:
   { query: [Getter],
     pathname: [Getter],
     asPath: [Getter],
     back: [Function: back],
     push: [Function: push],
     pushTo: [Function: pushTo],
     replace: [Function: replace],
     replaceTo: [Function: replaceTo] } }

Answer №1

Inside the swc class, you have already defined the props object, so there is no need to destructure the class itself.

You are attempting to access swc.props.swc.results when you should actually be accessing swc.props.results instead.


Overall, it appears that there may be an incorrect component setup, especially with the definition of your props. It seems that you are passing the results prop and then the swc component itself within the props.

Without further details, it is difficult to provide a precise answer. However, it is recommended to structure it as follows:

import React, { Component } from 'react'
import fetch from 'isomorphic-unfetch'

type Props = {
   results: any[], // < always try to be more specific than any[]
}

// Components in React should start with an uppercase letter based on convention
class Swc extends Component<Props, {}> {
  static async getInitialProps(ctx) {
     const res = await fetch("https://swapi.co/api/people/")
     const json = await res.json()
     return { json.swc.results }
  }

  render() {
     const { results } = this.props
     // React components should always return a singular tag 
     // (eg. div, React.Fragment, but not an array of <Layout>
     const renderResults = results && results.map(result => (
         <Layout>
            {result}
         </Layout>
     ))

      return (
        <>
          {renderResults}
        </>
      )

  }
}

export default Swc

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

The column must have a defined value and cannot be left empty

I encountered an issue while trying to populate a database with seed data. The error message I received is: name: 'SequelizeDatabaseError', parent: Error: Column 'id' cannot be null code: 'ER_BAD_NULL_ERROR', errno: 1048, sql ...

There was a DOMException in Angular because the transaction is not active when trying to execute 'getAll' on 'IDBObjectStore'

private get ctxMessage() { const messageTransaction = this.db.transaction('messages', 'readwrite'); const messageStore = messageTransaction.objectStore('messages'); return { messageTransaction, messageStore }; } ...

Using PHP to display a message box and redirecting to a different webpage

Currently, I am working on developing a login page using PHP. When the user enters an incorrect username/password combination, I display a JavaScript alert box to notify them. However, after clicking the "OK" button on the alert box, I want to redirect t ...

Updating a single .jshintrc option for a folder

My project has a .jshintrc file at the root, containing the following settings: { "node": true, "smarttabs": true, "undef": true, "unused": true } While these settings work well for node-related code in my project, they are not suitable for brows ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

JSON Novice - persistently storing data in JSON during browser refreshes

My AJAX poll was set up following a guide found here: http://www.w3schools.com/php/php_ajax_poll.asp Instead of storing the poll entries from an HTML radio button in an array within a text file as demonstrated in the tutorial, I wanted to save them in a J ...

Getting Anchor Javascript to Submit in Internet Explorer. Functioning in Firefox, Chrome, and Safari

Greetings Stackoverflow enthusiasts, I have been working on a raffle form where users can input their name and select their location from a dropdown list. After filling out the form, they can click submit and their information will be stored in a database ...

AngularJS and Handlebars (npm)

Is it possible for angularJS to function as a substitute for the "view engine" in nodeJS? I am seeking insights on the optimal method to use. (Do MEAN Stack developers utilize view engines? Or do they prefer using res.sendFile along with tools like ui-ro ...

How do I verify response values in Postman tests when the input parameter may be empty and can have multiple possible values?

In my program, there is an input parameter known as IsFruit that can have a value of either 0 or 1. If IsFruit is set to 0, the response should return fruits with a FruitsYN value of N. Similarly, if it is set to 1, FruitsYN should be Y. In cases where I ...

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Sharing data with external domains and retrieving HTML output using JavaScript

When a browser sends a POST request and expects an HTML page result from JavaScript, problems arise if there is no Access-Control-Allow-Origin in the server response. Unfortunately, changing anything on the server side is not an option. If a human clicks ...

The lack of invocation of Angular 4's ngOnInit function following a call to router

In my Angular application, I have 3 tabs where one tab displays a table listing employees. Initially, everything works well when the data is loaded for the first time in ngOnInit using an HTTP get request. However, after adding a new employee through a for ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...

Troubleshooting app.use in Next.js and express.js: Understanding the issue

Currently, I am working on a project using next.js along with a custom server (express.js). In my API endpoints, I want to utilize some middlewares (such as const attachUser), but strangely I am facing issues when trying to use app.use. The code seems to ...

What is the best way to clear an array?

Yesterday I had a query regarding JSON Check out this link for details: How to return an array from jQuery ajax success function and use it in a loop? One of the suggested answers included this script: setInterval(updateTimestamps,30000); var ids = new ...

Make sure to query MySQL database to see if the data already exists, and if not, go ahead and insert it using PHP

I am encountering difficulties in writing PHP code to insert values into a MySQL database only if they do not already exist. I am transmitting an array from JavaScript to a PHP file using $.ajax with the POST method. Do I need to include an additional &a ...

Enhancing Javascript functionality with additional on.change customization opportunities

My website currently has a dynamic AJAX script that updates a table based on the selection from a dropdown menu with the ID of [id="afl_player_ID"]. However, I am looking to extend this functionality so that the same script runs when either [id="afl_playe ...

Difficulty with conflicting styles when dynamically loading components in Nuxt3

I'm facing a challenge with my Nuxt 3 application where I need to dynamically load different Header components for Mobile and Desktop devices. I have created Header.vue and MobileHeader.vue for this purpose, and want to display them based on the dev ...

Issue with jQuery fadeIn() and fadeOut() functions on IE versions 7 and 8

I have a project in Ruby on Rails that showcases illustrations. The top of the page features category links that fade out the current illustrations, replace them with new content, and then fade back in. Currently, I am utilizing jQuery version 1.6.2 for t ...