I am trying to create a like button function in my react app.
Main challenge is that i need to handle like function depending on the login status of the user.
In my component:
import {LikeApi} from "../api/likeApi"
const myComponent = ({prodKey}) =>{
const likeHandler = ()=>{
const res = LikeApi(prodKey)
}
return (
<button onClick={likeHandler} />
)
}
In my Likeapi "module" (im trying to make this into a resuable module"):
import { useRecoilValue } from "recoil";
import { isLoggedInAtom } from "../recoil/AtomUser";
import { useNavigate } from "react-router-dom";
export const LikeApi = (prodSeq) => {
const navigate = useNavigate();
const isLoggedIn = useRecoilValue(isLoggedInAtom);
console.log(isLoggedIn);
if (!isLoggedIn) {
navigate("/login");
} else {
return isLoggedIn;
}
};
These are my basic setup.
when user clicks like button, likeApi module checks the login status from recoil (state management)
if user is not logged in, then navigate to login page.
eventually i will send api request to backend
The problem is:
directly calling recoil in my component works
import {LikeApi} from "../api/likeApi"
const myComponent = ({prodKey}) =>{
const res = LikeApi(fileSeq)
return (
<button onClick={likeHandler} />
)
}
But when i place LikeApi module (function) inside the button function, i get an error:
import {LikeApi} from "../api/likeApi"
const myComponent = ({prodKey}) =>{
const likeHandler = ()=>{
const res = LikeApi(prodKey)
// throws an error
}
return (
<button onClick={likeHandler} />
)
}
The error message is:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
My question is:
Is it not possible to get recoil value as i click a button?
Should i always first get recoil value (login status) only inside the component.