0

In our project we are using the MERN stack

I want to create a generic function whose input is the path to any api endpoint in our server and the JSON package to POST to the server. I want it to return the JSON sent back from the server.

That way when we are developing our mobile app and web app, we can simply use this function for all of our api endpoint POSTs.

I'm very new to using React/React-Native so I'm sure that I'm not understanding some sort of key concept.

Here is what I have so far:

import React from 'react';

// returns whatever the respective apiEndpoint is suppose to return
function postToAPI(route, package2send)
{
  async() =>
  {
    try
    {
      const payload = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: package2send
      }

      const res = await fetch(route, payload);
        console.log(res);
      const data = await response.json();
        console.log(data);
      return data;
    }
    catch(error)
    {
      console.error(error);
    }
  }
}

export default postToAPI;

Whenever I call this function from my Login.js after I

import { postToAPI } from './postToAPI'

I get this error: 'TypeError: Object(...) is not a function'

I'm sure there are multiple things wrong with this code, so if someone could steer me in the right direction, it would be greatly appreciated.

Anon
  • 99
  • 7

1 Answers1

2

If you export the function as default, you must import without bracket like that.

import  postToAPI  from './postToAPI';

If you would like to write a generic API call class, I advise you this class which I wrote before.

import { BASE_URL } from "../config";
import { Actions } from "react-native-router-flux";
import { deleteUserInfo } from "./SessionHelper";

const API_URL = BASE_URL;

class ApiHelper {
    private accessToken?: string;

  constructor() {
    this.accessToken = undefined;
  }

  setAccessToken = (accessToken: string) => {
    this.accessToken = accessToken;
  };

  getAccessToken = () => {
    return this.accessToken;
  };


  getRequest = async (endpoint: string) => {
    try {
      const response = await fetch(`${API_URL}${endpoint}`, {
        method: "GET",
        headers: {
          "x-access-token": `${this.accessToken}`
        }
      });
      const responseJson = await response.json();
      return responseJson;
    } catch (error) {
      console.error(error);
    }
  };

  postRequest = async (endpoint: string, body: any) => {
    try {
      const response = await fetch(`${API_URL}${endpoint}`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "x-access-token": `${this.accessToken}`
        },
        body: JSON.stringify(body)
      });
      
      const responseJson = await response.json();
      const finalResponse = { data: responseJson, status: response.status };

      if (response.status === 401) {
        deleteUserInfo();
        this.accessToken = undefined;
        Actions.auth();
      }

      return finalResponse;
    } catch (error) {
      console.error(error);
      return error;
    }
  };

  patchRequest = async (endpoint: string, body: any) => {
    try {
      const response = await fetch(`${API_URL}/${endpoint}`, {
        method: "PATCH",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "x-access-token": `${this.accessToken}`
        },
        body: JSON.stringify(body)
      });
      const responseJson = await response.json();
      const finalResponse = { data: responseJson, status: response.status };

      if (response.status === 401) {
        deleteUserInfo();
        this.accessToken = undefined;
        Actions.auth();
      }

      return finalResponse;
    } catch (error) {
      console.error(error);
    }
  };

  deleteRequest = async (endpoint: string, body: any) => {
    try {
      const response = await fetch(`${API_URL}/${endpoint}`, {
        method: "DELETE",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "x-access-token": `${this.accessToken}`
        },
        body: JSON.stringify(body)
      });
      const responseJson = await response.json();
      const finalResponse = { data: responseJson, status: response.status };

      if (response.status === 401) {
        deleteUserInfo();
        this.accessToken = undefined;
        Actions.auth();
      }

      return finalResponse;
    } catch (error) {
      console.error(error);
    }
  };
}

export const APIHelper = new ApiHelper();
İlker
  • 476
  • 3
  • 5