4

I made a UI with React Native, as well as a Cheerio.js scraper (with Cron Job to activate it once every day) I'll use to grab certain data from the web, so it can render in the UI. However, I have no idea how to link the two of them.

I am pretty sure I can do this with Express (which I am most comfortable with for the back-end), but can someone tell me exactly what I need to do to connect my front-end to a back-end?

Just in case, I am a junior dev (better on the front-end than the back-end) so please keep your answers simple. Even if your answers are more conceptual, rather than code-based, I'd really appreciate it.

halfer
  • 19,824
  • 17
  • 99
  • 186
Ryo-code
  • 1,460
  • 2
  • 10
  • 12

2 Answers2

3

API

I'm quite happy with GraphQL as an alternative to REST. However, there are many ways to connect through an api. Your client needs the link to where your server is running, and your server needs to enable that.

Tutorials

I think I couldn't explain it better than this tutorial (with example on Github): https://medium.com/react-native-training/react-native-with-apollo-server-and-client-part-1-efb7d15d2361

https://medium.com/react-native-training/react-native-with-apollo-part-2-apollo-client-8b4ad4915cf5

And following Stephen Grider's tutorial on Udemy for deeper understanding of GraphQL. He is using React and not React Native in his tutorial but the syntax remains very close. https://www.udemy.com/graphql-with-react-course/learn/v4/overview

Important notice - The first tutorials use "apollo-server" while udemy's tutorial uses graphql. apollo-server changes quite often and graphql may be clearer.

Example

Here's how my bridge between the two looks like. The biggest difficulty was dealing with Cors for the front-end version of the app (Next.js) and finding out that the server can be accessed on http://10.0.3.2:8080/graphql (may vary) instead of localhost:8080.

My index.android.js (client side):

import React from 'react'
import { AppRegistry } from 'react-native'
import App from './app'

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo'

const Client = () => {
  const networkInterface = createNetworkInterface({
   uri: 'http://10.0.3.2:8080/graphql'
  })
  const client = new ApolloClient({
    networkInterface
  });
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>)
}

AppRegistry.registerComponent('apolloclient', () => Client);

My app.js server side

const express = require('express');
// const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const chalk = require('chalk');

// New imports
// NEVER FORGET to require the models,
// in which schemas are registered for a certain model
// forgetting it would throw "Schema hasn't been registered for model..."
const models = require('./models');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// My mongoLab URI
const MONGO_URI = 'mongodb://xxx:xxx@xxx.mlab.com:xxx/xxx';

// mongoose's built in promise library is deprecated, replace it with ES2015 Promise
mongoose.Promise = global.Promise;

// Connect to the mongoDB instance and log a message
// on success or failure
mongoose.connect(MONGO_URI);
mongoose.connection.once('open', () => console.log(`${chalk.blue(`  Connected to MongoLab instance `)}`));
mongoose.connection.on('error', error => console.log(`${chalk.yellow(`⚠  Error connecting to MongoLab: ` + error + ` ⚠`)}`));

app.use(cors());

// We pass the schema as an option to our expressGraphQL middleware
app.use('/graphql', expressGraphQL({
  schema,
  graphiql: true
}))

module.exports = app;

my index.js (server side):

const app = require('./app');
const chalk = require('chalk');

const PORT = 8080;

app.listen(PORT, () => {
  console.log(`${chalk.green(`✔  Server started on http://localhost:${PORT} ✔`)}`);
});
Community
  • 1
  • 1
1

Assuming you're communicating with an API built with Express then use fetch as described in the docs: https://facebook.github.io/react-native/docs/network.html

Cisco
  • 20,972
  • 5
  • 38
  • 60
  • Thanks Francisco! I looked at a bunch of docs which were confusing to me, but this short youtube video shows fetch in action, and I managed to do exactly what I wanted! :D https://www.youtube.com/watch?v=xmgY37oc_B4 – Ryo-code Jul 14 '17 at 05:24
  • @Ryo-code the YouTube video you linked shows up as private and unavailable. Is there an alternative link to that video. – Ghos3t May 07 '20 at 22:13
  • Ahh... sorry. I linked that video three years ago. I have no idea what it was anymore; but I guess the link to the docs Francisco had should be fine. – Ryo-code May 09 '20 at 13:44