Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show loader from a helper function using react context api

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.

like image 530
Gvs Akhil Avatar asked Mar 24 '26 14:03

Gvs Akhil


1 Answers

You have two mistakes:

  1. useContext(LoaderContext) returns a tuple (with your implementation), so you need the setter function:
// Not [dispatch]
const [,dispatch] = useContext(LoaderContext);
  1. 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.

like image 128
Dennis Vash Avatar answered Mar 26 '26 02:03

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!