TS2339: The object does not have a property named 'users'

Transitioning from JavaScript to TypeScript while learning React has presented me with a new challenge.

The initial state for my context is blank, which is causing issues with accessing the properties.

If you prefer, here is the repository link: https://github.com/lets-c-whats/ts-github-finder/blob/main/src/components/users/UserResults.tsx

Context file

const GithubContext = createContext({});

interface GithubContextProps {
  children: React.ReactNode;
}

export const GithubProvider = ({ children }: GithubContextProps) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const fetchUsers = async () => {
    const response = await fetch(`${GITHUB_URL}/users`, {
      headers: {
        Authorization: `token ${GITHUB_TOKEN}`,
      },
    });

    const data = await response.json();

    setUsers(data);
    setLoading(false);
  };

  return (
    <GithubContext.Provider
      value={{
        users,
        loading,
        fetchUsers
      }}
    >
      {children}
    </GithubContext.Provider>
  );
};

export default GithubContext;

I have wrapped the App with the provider, and within the Home component is UserResults component

import { GithubProvider } from "./context/github/githubContext";
...
function App() {
  return (
    <GithubProvider>
      ...
      <Route path="/" element={<Home />} />
    </GithubProvider>
  );
}

After that, I am trying to access the values inside the component using the useContext hook

// DEPENDENCIES
import { useEffect, useContext } from "react";
import GithubContext from "../../context/github/githubContext";



function UserResults() {
  const {users, loading, fetchUsers} = useContext(GithubContext)

  useEffect(() => {
    fetchUsers()
  })

  if (!loading) {
    return (
      <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
        {users.map((user) =>) {
          return <UserItem key={user.id} userData={user} />;
        })}
      </div>
    );
  } else {
    return <Spinner />
  }
}
export default UserResults;

Even after all this effort, the app isn't functioning correctly, as it throws these errors:

TS2339: Property 'users' does not exist on type '{}'.
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |          ^^^^^

ERROR in src/components/users/UserResults.tsx:10:17

TS2339: Property 'loading' does not exist on type '{}'.
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |                 ^^^^^^^

ERROR in src/components/users/UserResults.tsx:10:26

TS2339: Property 'fetchUsers' does not exist on type '{}'.
     8 |
     9 | function UserResults() {
  > 10 |   const {users, loading, fetchUsers} = useContext(GithubContext)
       |                          ^^^^^^^^^^

ERROR in src/components/users/UserResults.tsx:19:21

TS7006: Parameter 'user' implicitly has an 'any' type.
    17 |     return (
    18 |       <div className="grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2">
  > 19 |         {users.map((user) => {
       |                     ^^^^

Answer №1

Make sure to specify the types for your context in order to avoid any issues. Here is a suggested improvement:

type UserContextTypes = {
    userList: User[];
    isLoading: boolean;
    retrieveUsers: () => void;
}

const UserContext = createContext({} as UserContextTypes);

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

Effortlessly glide through entire pages using the mouse wheel for seamless scrolling

I provide a seamless full-page scrolling experience using the mouse wheel. However, the scrollIntoView function does not seem to function within the @HostListener('wheel', ['$event']). Here is a snippet from app.component.html file: & ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

The reason for the Jest failure is that it was unable to locate the text of the button

As someone who is new to writing tests, I am attempting to verify that the menu opens up when clicked. The options within the menu consist of buttons labeled "Edit" and "Delete". However, the test fails with the message: "Unable to find an element with te ...

What is the best way to update the state of a response from an API call for a detailed object using React context, so that there is no need to retrigger the API call

I'm currently developing a react native typescript project. How can I assign the data received from an API call to my context object? I want to avoid making the API call every time the component is loaded. Instead, I want to check if the context alr ...

Guide to Implementing Dependency Injection in Angular 2

When working with Angular Components written in TypeScript, it is possible to declare a class member (variable) as a parameter of the constructor. I am curious about the reason for doing so. To clarify, take a look at the examples below. Both achieve the ...

What could be the reason for the tsc command not displaying compilation errors when compiling a particular file?

My file, titled app.ts, contains the following code snippet: interface Foo { bar:String; } const fn = (foo? :Foo) => foo.bar; When I run tsc from the root folder with strict:true in my tsconfig.json file, I receive an error message like this ...

Error types in AxiosResponse and UseQueryResult encountered

Currently, I am utilizing react query within my typescript project. export type ImageData = { title: string; description: string; imgUrlOne: string; imgUrlTwo: string; }; export const fetchImageData = async (): Promise< AxiosResponse<Image ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Using Angular 4 to retrieve a dynamic array from Firebase

I have a dilemma while creating reviews for the products in my shop. I am facing an issue with the button and click event that is supposed to save the review on the database. Later, when I try to read those reviews and calculate the rating for the product, ...

What is the correct way to invoke a function from a separate file in typescript?

I am new to typescript and still learning. I have a question regarding calling a function defined in file B from file A. Can someone guide me on how to achieve this? ...

The TypeScript compiler is tolerant when a subclass inherits a mixin abstract class without implementing all its getters

Update: In response to the feedback from @artur-grzesiak below, we have made changes to the playground to simplify it. We removed a poorly named interface method and now expect the compiler to throw an error for the unimplemented getInterface. However, the ...

Utilizing Angular Validators.email with the ability to accept null values

In my .ts file, I have an Angular validator set up like this: this.detailsForm = formBuilder.group( { email: ['', Validators.compose([Validators.email])] }); While this setup works fine, the email validator also applies the required validat ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

Troubleshooting: Resolving JSX props issue in Vue template

Ever since integrating the FullCalendar library into my Vue project, I've been encountering an error every time I try to use my custom component in a Vue template. My setup includes Vue 3, Vite, VSCode, eslint, and prettier. This issue seems to be m ...

What is the best way to transfer a Blob image from Angular2 to NodeJs?

Encountering difficulties while attempting to upload a photo from the frontend. There is an input file where a file can be selected from the computer. The goal is to send that photo to the backend and store it as a Blob. Initially trying to retrieve the ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

Creating Instances of Parameterized Types

Consider the following scenario: class Datum {} An error message (error TS2304: Cannot find name 'T') is encountered when attempting the following: class Data<T extends Datum> { datum: T constructor() { this.datum = new ...

Ensuring data types for an array or rest parameter with multiple function arguments at once

I am looking for a way to store various functions that each take a single parameter, along with the argument for that parameter. So far, I have managed to implement type checking for one type of function at a time. However, I am seeking a solution that al ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...