I am pretty new to React Context API. What I am trying to do is set a loader when I perform an API call and stop the loader after an API call is done. But if I do these dispatch actions from helper function, I am getting an error:
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 fix this problem.
// ApiCalls.js
export const LoginService = (username, password) => {
//to show loader when api call starts
const [dispatch] = useContext(LoaderContext);
dispatch({
type: "SHOWLOADER",
payload: true
});
}
// Hello.js
export default function Hello(props) {
useEffect(() => {
LoginService();
}, []);
return(
<h2>Hello</h2>
)
}
Reproducible example.
You have two mistakes:
useContext(LoaderContext) returns a tuple (with your implementation), so you need the setter function:// Not [dispatch]
const [,dispatch] = useContext(LoaderContext);
LoginService is actually a custom hook, and shouldn't be called inside other hook (See Rules of hooks).import { LoaderContext } from './LoaderContext';
import {useContext, useEffect} from 'react';
// Use username,password
export const useLoginService = (username, password) => {
const [, dispatch] = useContext(LoaderContext);
useEffect(() => {
dispatch({
type: "SHOWLOADER",
payload: true,
});
}, []);
};
// Usage
export default function Hello(props) {
useLoginService();
return(
<h2>Hello</h2>
)
}
See fixed example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With