Karam Singh
Karam Singh

Reputation: 27

when I go to Auth page it shows blank page due to Error

In my website that I'm making when I try to go to Authpage it shows error Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) in my signup.js

import React, { useState } from "react";
import { Button } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { useContext } from "react";
import { UserContext } from "./Context";
import { initializeApp } from "@firebase/app";
import {
  getAuth,
  RecaptchaVerifier,
  signInWithPhoneNumber,
} from "firebase/auth";
import { signup } from "../../Actions/Auth";
import "./Auth.css";

function SignUpCard({ toggleCardFunc }) {
  var firebaseConfig = {
    apiKey: "*****",
    authDomain: "*****",
    projectId: "*****",
    storageBucket: "******",
    messagingSenderId: "******",
    appId: "********",
    measurementId: "*******",
  };

  const app = initializeApp(firebaseConfig);
  const auth = getAuth(app);
 const [isLogin, setIsLogin] = useContext(UserContext);  #here get error in this line on isLogin
  const [checked, setchecked] = useState(false);
  const [OTP, setOTP] = useState("");
  const [displayOtp, setDisplayOTP] = useState(false);
  const [user, setUser] = useState({
    name: "",
    email: "",
    password: "",
  });
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const handleCred = (e) => {
    let name = e.target.name;
    let value = e.target.value;
    setUser({ ...user, [name]: value });
  };

  const configureRecaptcha = () => {
    window.recaptchaVerifier = new RecaptchaVerifier(
      "sign-in-button",
      {
        size: "invisible",
        callback: (response) => {
          // reCAPTCHA solved, allow signInWithPhoneNumber.
          handleLogin();
          console.log("Captcha Verified ");
        },
        defaultCountry: "IN",
      },
      auth
    );
  };

  const handleLogin = () => {
    const phoneNumber = "+91" + user?.phoneNo;
    console.log(phoneNumber);
    configureRecaptcha();
    const appVerifier = window.recaptchaVerifier;
    signInWithPhoneNumber(auth, phoneNumber, appVerifier)
      .then((confirmationResult) => {
        // SMS sent. Prompt user to type the code from the message, then sign the
        // user in with confirmationResult.confirm(code).
        window.confirmationResult = confirmationResult;
        console.log("OTP has been sent");
        setDisplayOTP(true);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  const validateOTP = () => {
    if (OTP.length !== 6) return;
    window.confirmationResult.confirm(OTP).then((result) => {
      // User signed in successfully.
      const userResult = result.user;
      // console.log(JSON.stringify(userResult))
      alert("User is verified");
      dispatch(signup(user));
      setIsLogin(true);
      navigate("/");
    });
  };
  return (
    <div className="auth">
      {!displayOtp ? (
        <div className="authWrap">
          <div>
            <p>Display Name</p>
            <input type="text" onChange={handleCred} name="name" />
          </div>
          <div>
            <p>Email</p>
            <input type="email" onChange={handleCred} name="email" />
          </div>
          <div>
            <p>Phone No</p>
            <input type="text" onChange={handleCred} name="phoneNo" />
          </div>
          <div>
            <p>Password</p>
            <input type="password" onChange={handleCred} name="password" />
          </div>
          <div className="tc">
            <input
              type="checkbox"
              name="tc"
              onChange={() => setchecked(!checked)}
              checked={checked}
            />
            <p>
              Opt-in to receive occasional product updates, user research
              invitations, company announcements, and digest.
            </p>
          </div>
          <div id="sign-in-button"></div>
          <div className="login-button">
            {user.name !== "" &&
            user.email !== "" &&
            user.password !== "" &&
            checked ? (
              <Button
                onClick={handleLogin}
                style={{
                  marginTop: "1.5rem",
                  height: "2.3rem",
                  background: "#0a95ff",
                  boxShadow: "inset 0 1px 0 0 hsl(0deg 0% 100% / 40%)",
                  color: "white",
                  fontSize: "0.813rem",
                  textTransform: "capitalize",
                }}
              >
                Sign Up
              </Button>
            ) : (
              <Button
                disabled
                style={{
                  marginTop: "1.5rem",
                  height: "2.3rem",
                  background: "#868686",
                  boxShadow: "inset 0 1px 0 0 hsl(0deg 0% 100% / 40%)",
                  color: "white",
                  fontSize: "0.813rem",
                  textTransform: "capitalize",
                }}
              >
                Sign Up
              </Button>
            )}
          </div>
        </div>
      ) : (
        <div>
          <p>Enter OTP send to {user?.phoneNo}</p>
          <input
            type="password"
            onChange={(e) => setOTP(e.target.value)}
            name="name"
          />
          <div className="login-button">
            <Button
              onClick={validateOTP}
              style={{
                marginTop: "1.5rem",
                height: "2.3rem",
                background: "#0a95ff",
                boxShadow: "inset 0 1px 0 0 hsl(0deg 0% 100% / 40%)",
                color: "white",
                fontSize: "0.813rem",
                textTransform: "capitalize",
              }}
            >
              Submit OTP
            </Button>
          </div>
        </div>
      )}
      <div className="login-signup">
        <p>
          Already have an account?{" "}
          <span style={{ cursor: "pointer" }} onClick={toggleCardFunc}>
            Log in
          </span>
        </p>
        <p>
          {" "}
          Are you an employer? <span> Sign up on Talent </span>
        </p>
      </div>
    </div>
  );
}

export default SignUpCard;

And here context.js which I'm importing

import { useState, createContext } from "react";

export const UserContext = createContext();

export const UserProvider = ({ children }) => {
  const [isLogin, setIsLogin] = useState(false);
  return (
    <UserContext.Provider value={[isLogin, setIsLogin]}>
      {children}
    </UserContext.Provider>
  );
};

I have tried to put what was suggested by vscode above the line that gives error

 // eslint-disable-next-line no-unused-vars
  const [isLogin, setIsLogin] = useContext(UserContext);

but still getting the same error ------- Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) in both login.js and signup.js at the same lineyour text

Then I tried to comment the line and got the page but can't able to login because of commentting the line

can please someone help and tell what the issue is so that my code can work I'm just getting blank page right now with the above issue please someone suggest something provide answer

Upvotes: 1

Views: 627

Answers (1)

BALBIR SINGH
BALBIR SINGH

Reputation: 43

You are getting this error because you didn't wrap your components inside UserProvider. You can do that for example in index.js after importing it at the top, like so:

import {UserProvider} from "./path/context"; // ⚠️ use the correct path

...

root.render(
  <Provider store={store}>
    <React.StrictMode>
     <UserProvider>
      <App />
     </UserProvider>
    </React.StrictMode>
  </Provider>
);

Upvotes: 1

Related Questions