Uncaught (in promise) TypeError: ‘serviceCall’ is not a function


I am trying to persist the data of a user authenticated with AOuth2 (Google Account), but I have problems making the request to the API using contexts.

But when logging in and sending the tokenId of the user, it shows me the following error:
Unhandled Rejection (TypeError): serviceCall is not a function

Request to the API provider:

import { useGoogleAuth } from "../providers/authentication";
import { useApi } from "../providers/API";

export const useUsers = () => {
  const { signOut }: any = useGoogleAuth();
  const { serviceCall, setTokenId }: any = useApi();

  const signInUser = (tokenId: string) => {
    serviceCall("/users/signin", "GET", tokenId)
      .then(() => console.log("User signed in"))
      .catch(() => {
        signOut();
        setTokenId();
      });
  };

  return {
    signInUser,
  };
};

API provider:

import React, { useState } from "react";
import { useHistory } from "react-router-dom";

// context
import { useGoogleAuth } from "./authentication";

const ApiContext = React.createContext({});

interface IAPIProviderProps {
  children: React.ReactNode;
}

interface IServiceCallProps {
  endpoint: string;
  method: string;
  tokenId: string;
  request?: any;
}

export const APIProvider = ({ children }: IAPIProviderProps) => {
  const [tokenId, setTokenId] = useState();
  const { signOut }: any = useGoogleAuth();
  const history = useHistory();

  const serviceCall = async (props: IServiceCallProps) => {
    const {endpoint, method, tokenId, request} = props;

    const url = `${process.env.REACT_APP_API_URL}${endpoint}`;

    const response = await fetch(url, {
      method,
      body: JSON.stringify(request),
      headers: {
        "Content-Type": "application/json",
        Authorization: tokenId,
      },
    });

    if (response.ok) {
      return response.json();
    } else {
      const status = response.status;
      switch (status) {
        case 401:
          signOut();
          history.push("/login");
          break;
        case 403:
          history.push("/no-access");
          break;
        default:
          throw new Error();
      }
    }
  };

  const value = {
    serviceCall,
    setTokenId,
    tokenId,
  };

  return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;
};

export const useApi = () => React.useContext(ApiContext);

Note: I find it a bit difficult because I have started using typescript recently and all the validations it does are difficult for me.

Source: React – Stack Overflow

October 20, 2021
Category : News
Tags: oauth-2.0 | react-context | reactjs | typescript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.