Home > Net >  React. UserContext is not a function
React. UserContext is not a function

Time:07-29

I have this error

Uncaught TypeError: UserContext is not a function at UserAuth (AuthContext.js:26:1) at Signup (Signup.js:11:1)

AuthContext.js

import { createContext } from 'react'
import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  signOut,
  onAuthStateChanged
} from "firebase/auth"
import { auth } from "../firebase"

const UserContext = createContext()

export const AuthContextProvider = ({children})  => {

  const createUser = (email, password) => {
    return createUserWithEmailAndPassword(auth, email, password)
  }

  return (
    <UserContext.Provider value={createUser}>
      {children}
    </UserContext.Provider>
  )
}

export const UserAuth = () => {
  return UserContext(UserContext)
}

Signup.js

const {createUser} = UserAuth()

Any help?

CodePudding user response:

You are calling UserContext which is not a function. What you are looking for is React.useContext(). In your example

export const UserAuth = () => {
  return React.useContext(UserContext);
}

CodePudding user response:

Are you using the context in the App.js file? Using context just requires importing it and calling it!

ALso, check this article, https://dev.to/dancurtis/learn-to-usecontext-with-hooks-in-3-minutes-4c4g

It is really helpful.

CodePudding user response:

The error is stating that UserContext is not a function and you are calling UserContext as a function at this part of your code:

export const UserAuth = () => {
  return UserContext(UserContext)
}

From your code, I'm assuming that you're trying to export the UserContext to use it in other places.

In this case, you should export the UserContext variable first:

export const UserContext = createContext()

And in the other pages you can use React.useContext, like this:

import { UserContext } from "AuthContext.js";

const MyComponent = () => {
    const userContext = React.useContext(UserContext);
    userContext.createUser('[email protected]', 'password');
}
  • Related