Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to destructure useContext hook in Typescript with null default value?

I created context with null initial value that I am now accessing in other component.
However when I destructure it to access the variables form the context then I get ts error:

Property 'users' does not exist on type 'GithubContextProps

function UserResults() {
  const appContext = useContext(GithubContext)

  const { users, loading, fetchUsers } = appContext
  

  useEffect(() => {
    fetchUsers()
  }, [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 : User) => (
          <UserItem key={user.id} user={user} />
        ))}
      </div>
    )
  } else {
    return <Spinner />
  }
}

And here is where i created context:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export type User = {
  id: number;
  login: string;
  avatar_url: string;
}

interface GithubContextProps {
  users: User[];
  loading: boolean;
  fetchUsers: () => void;
}


const GithubContext = createContext<GithubContextProps | null>(null)

I tried solving this with using conditional checking whether appContext is not null but then useEffect will throw errors that it cannot be used conditionally in this component. Any idea how to solve it without resorting to turning off React strict mode?

>Solution :

How about:

const { users, loading, fetchUsers } = appContext ?? {};

You’ll get undefined when appContext is null.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading