I tried to implement the Google login in my React app using refinejs. I was trying to make a React app using refine and other packages. I was following a course on YouTube. I almost followed the YouTuber until this step, but my code was giving error while his wasn't.
But this error popped up.
The below is my code.
import { useEffect, useRef } from "react";
import { useLogin } from "@pankod/refine-core";
import { Container, Box } from "@pankod/refine-mui";
import { yariga } from "../assets";
import { CredentialResponse } from "../interfaces/google";
export const Login: React.FC = () => {
const { mutate: login } = useLogin<CredentialResponse>();
const GoogleButton = (): JSX.Element => {
const divRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (typeof window === "undefined" || !window.google || !divRef.current) {
return;
}
try {
window.google.accounts.id.initialize({
ux_mode: "popup",
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
callback: async (res: CredentialResponse) => {
if (res.credential) {
login(res);
}
},
});
window.google.accounts.id.renderButton(divRef.current, {
theme: "filled_blue",
size: "medium",
type: "standard",
});
} catch (error) {
console.log(error);
}
}, []); // you can also add your client id as dependency here
return <div ref={divRef} />;
};
return (
<Box
component="div"
sx={{ backgroundColor: "#FCFCFC" }}
>
<Container
component="main"
maxWidth="xs"
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
height: "100vh",
}}
>
<Box
sx={{
display: "flex",
justifyContent: "center",
flexDirection: "column",
alignItems: "center",
}}
>
<div>
<img src={yariga} alt="Yariga Logo" />
</div>
<Box mt={4}>
<GoogleButton />
</Box>
</Box>
</Container>
</Box>
);
};

The error was TS2322:
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
And so this line:
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,needs to be changed to:
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID as string,cast it as string thus telling TypeScript: I am sure this is a string, thus converting it.