Search code examples
ruby-on-railsrubypostgresqlreact-nativefetch

Rails server with React Native project getting error: Unhandled promise rejection: TypeError: Object is not a function


I am a beginner to Ruby on Rails. Currently have a Ruby on Rails server that I'm trying to get to interact with a React Native/Expo app. I am spinning up the server using rails s and it seems to be running with the following output

=> Booting Puma
=> Rails 5.2.4.6 application starting in development 
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.6 (ruby 2.6.6-p146), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

In another terminal window I'm starting a postgresql database using the following command: pg_ctl -D /usr/local/var/postgres start

All seems good.

I'm making a sample call to the server. It doesn't seem to reach the server and I get the following output:

[Unhandled promise rejection: TypeError: Object is not a function (near '...fetch...')]
at screens/rankingsPage/Rankings.jsx:28:22 in handlePress
at screens/rankingsPage/Rankings.jsx:28:22 in handlePress
at node_modules/react-native/Libraries/Pressability/Pressability.js:691:17 in _performTransitionSideEffects
at node_modules/react-native/Libraries/Pressability/Pressability.js:628:6 in _receiveSignal
at node_modules/react-native/Libraries/Pressability/Pressability.js:524:8 in responderEventHandlers.onResponderRelease
at [native code]:null in forEach
at [native code]:null in callFunctionReturnFlushedQueue

Here is my fetch call. Does anyone know what the problem is and how I can fix this? Thanks.

export const emailNewAccount = async (email, password, passwordConfirmation, username) => {
  console.log("test call"); // <-- successfully logging
  const url = `${serverUrl}/api/v1/create_account`; // <-- "http://localhost:3000/api/v1/create_account
  const responseData = await fetch(url, {
    headers: { "Content-Type": "application/json" },
    method: "POST",
    body: JSON.stringify(email, password, passwordConfirmation, username)
  });

  const json = await responseData.json();
  console.log("json : ", json); // <-- not logging

  return json;
};

Solution

  • As it turned out, the person working on the server had used node-fetch as an import.

    import * as fetch from "node-fetch";
    

    So when using fetch, rather than using the native fetch we were using node-fetch. When we commented out the import (or deleted it), and simply used the fetch that is native to React Native, it worked.