2

I am newbie in React Native, I made a simple back-end using Mongodb and express routes etc in MongoDb atlas. I am successfully able to post/get/patch/Delete operation on mongodb atlas that store Title and Description using Postman. Everything is working fine.

Here comes the problem First when i make a simple frontend in ReactNative that take inputs Title and Description. I want application that take simple input of Title and Description and on Submit Button it store into the the mongodb Atlas just like postman is doing. I tried but its not working code is below. I dont know how to communicate the front end into backend. I watch alot of tutorials but unable to get the point.

Secondly, when i make a server i wrote in pakage.json > "start": "nodemone server.js" and i need to run ReactNative app i update the pakage.json > "start": "expo start" to run app. How can i run server and expo app same time? if i seprate the app folder then how can i connect both of them. below is my Code.

Routes folder post.js

const express = require( 'express' );
const router = express.Router();
const Post = require ('../models/Post')

//Gets back all the posts
router.get ( '/', async (req, res) =>{
    try{
      const post = await Post.find();
      res.json(post);
    }catch (err) {
      res.json({message: err })
    } 
  });

//To Submit the Post
router.post('/', async (req, res) =>{
  //console.log(req.body);
  const post = new Post({ 
    title: req.body.title,
    description: req.body.description
  });
  try{
    const savedPost = await post.save();
    res.json(savedPost);
  }catch (err) {
    res.json ({ message: err })
  }
});

//Get back specific Post
router.get('/:postId', async (req, res) =>{
  try{
  const post=  await Post.findById(req.params.postId);
  res.json(post);
  }catch(err) {
    res.json({message: err });
  }
})
// to delete specific post 
router.delete('/:postId', async (req, res) =>{
  try{
  const removePost=  await Post.remove({_id: req.params.postId});
  res.json(removePost);
  }catch(err) {
    res.json({message: err });
  }
})

//update Post
router.patch('/:postId', async (req, res) =>{
  try{
  const updatePost =  await Post.updateOne(
    {_id: req.params.postId}, 
    { $set: 
      {title: req.body.title}
    }); 
  res.json(updatePost);
  }catch(err) {
    res.json({message: err });
  }
})

module.exports = router;  

Defined Schema Post.js

const mongoos = require( 'mongoose' );

const PostSchema = mongoos.Schema ({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now 
    }
})

module.exports = mongoos.model ('Post', PostSchema); // giving this schma name Post  

server.js

const express = require( 'express' );
const app = express();
var mongo = require('mongodb');
const mongoos = require( 'mongoose' );
const bodyParser = require('body-parser');
require('dotenv/config');
const postRoute = require('./Routes/post');

app.use(bodyParser.json());
app.use ('/post', postRoute);

app.get ( '/', (req, res) =>{
  res.send('We are on Home ')
});


// connecting to database
mongoos.connect(
  process.env.DB_CONNECTION, 
  { useNewUrlParser: true },
  () => console.log('Connected to db')
);

app.listen(3000);

Frontend Form.js

import React from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';



class Form extends React.Component{
    constructor(){
        super();
        this.State = {
            title: '',
            description: ''
        } 
    }

    getInput(text, field){
        if(field == 'title')
        { 
            this.setState({ title: text, })
        }
        else if(field == 'description')
        {
            this.setState({ description: text, })
        }
        //console.warn(text)
    } 

    submit(){
        let collection={}
        collection.title = this.state.title,
        collection.description = this.state.description;
        console.warn(collection);  
        var url = process.env.DB_CONNECTION ;
        fetch(url, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                collection
            }),
        });
    }

    render() {
      return (
        <View style={styles.container}> 

            <TextInput style={styles.inputBox} 
              underlineColorAndroid= 'rgba(0,0,0,0)'
              placeholder='Title'
              selectionColor="#fff" 
              keyboardType="default"
              onChangeText = {(text) => this.getInput(text, 'title')}
            />

            <TextInput style={styles.inputBox} 
              multiline = {true}
              numberOfLines = {4}
              underlineColorAndroid= 'rgba(0,0,0,0)'
              placeholder='Description'
              selectionColor="#fff" 
              keyboardType="default"
              onChangeText= {(text) => this.getInput(text, 'description')}
            />

            <TouchableOpacity onPress={()=>this.submit()} style={styles.btn} >
                <Text style={{textAlign: 'center'}}>Submit</Text>
            </TouchableOpacity>

        </View>
    );
    }
}  

export default Form; 
7
  • 1
    hie Abdul! I hope you are doing fine. I would recommend using axios or fetch in order to communicate from app side to your Api side. for further please reach out Commented Dec 4, 2019 at 10:39
  • I tried fetch(on last part of my code). can you please see that what i am missing ? and how i can run the server and expo app same time Commented Dec 4, 2019 at 10:43
  • 1
    what is the response of that fetch call! and you are using what package to use DOT_ENV api structure in react-native Commented Dec 4, 2019 at 10:47
  • 1
    i see you are not using . either ASYNC/AWAIT or ThenCatch after hitting the url end point from fetch Commented Dec 4, 2019 at 11:06
  • 1
    Let us continue this discussion in chat. Commented Dec 4, 2019 at 21:56

1 Answer 1

4

Here comes a very basic solution to your problem:

1: if you are using Rest API based model of communication go for Two separate repos on GITHUB. One for React native app of yours and one for server-side of yours.

2: now to go to Heroku.com and make an app there and attach your card there in order to use the full Free Sandbox functionality

3: create a project there and find an option to deploy from Github.

4: for data communication aka network requests its easy to use axios rather than Fetch

for best practices use :

https://riptutorial.com/react-native/topic/857/getting-started-with-react-native

5: in order to run more than one command in package json able to run multiple scripts in package.json you can either do it like

scripts:{"run": "yarn start" && "react-native-expo"}

6: or if your scripts are like they gonna need to run constantly in the background it's better that you create two separate scripts

scripts:{"run1": "yarn start", "run2":"yarn start2"}

7: I see you are not handling the AsyncAwait Try catch or Promise after the fetch

8: you are also not hitting the server-side URL seemingly you are hitting DB connection url. what you should be doing is that you hit the POST/GET/UPDATE routing endpoint of yours

Sign up to request clarification or add additional context in comments.

2 Comments

That's work. waho.. i was stuck in this from last two days. much thanks for your help. I looking fwd to move on heroku and github. as a new bie its a big thing for me !!
Hello Abdul Wahab, can you please show how you did it. I am having the same problem but after going through the answers provided by Rizwan i still got an error saying "[Unhandled promise rejection: TypeError: Network request failed]".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.