Creating a standard arrow function in React using TypeScript: A Step-by-Step Guide

I am currently working on developing a versatile wrapper component for Apollo GraphQL results. The main objective of this wrapper is to wait for the successful completion of the query and then render a component that has been passed as a prop. The component passed in should have props of type QueryResult<T>.

When I run this snippet of code, I encounter an error at Column 66 which states:

Cannot find name 'T'.ts(2304)

import React from 'react';
import { QueryResult } from 'react-apollo';
import { useSandboxContext } from 'src/js/shared/components/SandboxContext';
import { ErrorContent } from 'src/js/shared/components/ErrorContent';
import { PageSpinner } from 'src/js/shared/components/PageSpinner';

interface WrapperComponentProps<T> extends QueryResult<T> {
  // TODO: determine how to specify that the wrapped component takes the results
  // Perhaps something like this `React.ReactType<QueryResult<T>>` but it triggers errors
  wrappedComponent: React.ReactType;
}

// Receiving an error from `React.FC<WrapperComponentProps<T>>`
// `Cannot find name 'T'.ts(2304)`
export const ApolloResultWrapper: React.FC<WrapperComponentProps<T>> = <T extends object>(props: WrapperComponentProps<T>) => {
  const sandbox = useSandboxContext();

  if (props.error) {
    sandbox.logger.error('query failed', props.error);

    return <ErrorContent />
  }
  if (props.loading) {
    return <PageSpinner />;
  }

  if (!props.data) {
    return <ErrorContent />
  }

  // TODO: determine how to spread all the props except wrappedComponent
  return <props.wrappedComponent {...props} wrappedComponent={undefined} />;
}

Answer ā„–1

Finally resolved the problem

interface WrappedComponentProps<T> {
  details: T
}

interface WrapperComponentProps<T, K> {
  apolloResponse: QueryResult<T>;
  wrappedElement: React.ComponentType<WrappedComponentProps<T> & K>;
  componentProperties: Omit<K, keyof WrappedComponentProps<T>>;
}

type ElementProperties<T, K> = React.PropsWithChildren<WrapperComponentProps<T, K>>;

export const ApolloResponseWrapper = <T extends object, K = {}>(props: ElementProperties<T, K>) => {
  const sandbox = useSandboxContext();

  if (props.apolloResponse.error) {
    sandbox.logger.error('Something went wrong', props.apolloResult.error);

    return <ErrorContent />
  }
  if (props.apolloResponse.loading) {
    return <PageSpinner />;
  }
  if (!props.apolloResponse.data) {
    return <ErrorContent />
  }

  return <props.wrappedElement
    children={props.children}
    details={props.apolloResponse.data}
    {...props.componentProperties as K}
  />;
}

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

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

How can one use an express post request to direct the client to the login page forcefully?

I am implementing secure backend routes that run a verifyJWT function before retrieving data. Is there a way to automatically redirect the client to the login page if the token is expired or invalid? Using res.redirect("/login") did not have any effect on ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...

Sorting JSON arrays in Typescript or Angular with a custom order

Is there a way to properly sort a JSON array in Angular? Here is the array for reference: {"title":"DEASDFS","Id":11}, {"title":"AASDBSC","Id":2}, {"title":"JDADKL","Id":6}, {"title":"MDASDNO","Id":3}, {"title":"GHFASDI","Id":15}, {"title":"HASDFAI","Id": ...

Can we find a method to decrease this data usage?

I'm struggling to phrase my question, so here's a visual representation: I have developed a card browsing React web application that downloads 50mb of images lazily when a user visits the page. The actual app is only 1mb in size. These images a ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

Issues with initializing React code - A beginner's guide to troubleshooting in React development

The div ID specified on line 9 is not being displayed as expected. The output does not include the text placed under the reactDom.render function. It only shows "Hello World from the index" on line 10. What could be causing this issue? I am utilizing t ...

Can you identify the type of component being passed in a Higher Order Component?

I am currently in the process of converting a protectedRoute HOC from Javascript to TypeScript while using AWS-Amplify. This higher-order component will serve as a way to secure routes that require authentication. If the user is not logged in, they will b ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

React developers frequently use Axios to make multiple requests

When trying to get user information for my Navbar by fetching a local token, my Axios function seems to be sending requests multiple times (up to 12 times) without any apparent reason: Below is the code I am using: const history = useHistory() const [user ...

The Material-ui Select component is experiencing issues with updating the state accurately

When creating a multiple select input using Material-UI, I encountered an issue with setting the default selected values from state. Despite having an array of two objects in the state and setting it as the select value, the default objects are not being ...

Any ideas on addressing the issue of infinite rendering in useEffect() due to searchbar input?

I've been working on this Functionality Code and encountered a frustrating issue. Despite checking everything with console log, the error seems to be infinite when I apply setProducts. Can someone offer any insights or solutions? const Header = () =& ...

Dividing a collection of URLs into smaller chunks for efficient fetching in Angular2 using RxJS

Currently, I am using Angular 2.4.8 to fetch a collection of URLs (dozens of them) all at once. However, the server often struggles to handle so many requests simultaneously. Here is the current code snippet: let collectionsRequests = Array.from(collectio ...

"Implementing a onClick method to render a component in React with passed props ā€“ a complete

Is there a way to properly update the LatestTweetsComponent with data fetched in handleRequest? The `tweets` are correctly updating onClick, but the LatestTweetsComponent is not rendering or updating as expected. It seems like my current approach might b ...

Maintaining state across interconnected tables in React for seamless communication [data grid]

I encountered an issue in my React app with TypeScript while using the Material UI library, specifically related to preserving the state of two datagrids and syncing them after a page refresh. Objective The goal is to have a datagrid/table where users ca ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...

Navigating through a node tree and making changes to its configuration and content

Here's the input I have. Some nodes have downlines with multiple other nodes nested inside. data = [ { "user_id": "1", "username": "johndoe001", "amount": "0.00", "down ...

Trouble with using setState within onChange function

Iā€™m on a mission to understand why this method is effective const Navigation:React.FC = () =>{ const [Volume, setVolume] = useState<number>(50) const onChange = (event) => { setVolume(event.target.value); } return( ...

Customizable Button component featuring background image options

Need help with creating a versatile Button component in React that can easily accommodate different sizes and shapes of background images? This is how my current implementation looks like - Button.js const Button = ({ url }) => { const inl ...

The Yarn Start Command encountered a hiccup and exited with error code 1

Recently, I created a React app using create-react-app and installed react-admin. However, when I attempted to start the development server with yarn start, an error occurred that was unhandled and stated "Command failed with exit code 1." Even after con ...