-1

I am new to react native and I am creating an app that displays a list fo podcasts which are stored in a mysql database. I then use php to get the information and convert it to json format. Once the information is covered to json I then fetch it within react native and display it within a flatlist.

I would like a notification to appear each time the podcast list has been update.

I have set up my notifications using onesignal and use node.js on my backend to create and send the notifications.

I would like to be able to listen to the database to check each time that the database has a new row and then covert this into react native so that I can send the notifications.

After doing some research I have been unable to find a solution for this.

Here is my php

 <?php


include 'DBConfig.php';

$json = file_get_contents('php://input');

$obj = json_decode($json, true);

$id = $obj['id'];

$query = "SELECT * FROM SermonsTable WHERE Category ='$id'";

$result = mysqli_query($con, $query) or die("Invalid Query");

while($row = mysqli_fetch_assoc($result)){ 
        $Item[] = $row;
        $json = json_encode($Item);
    }
    
echo $json;

    ?>

React Native file

export default class MainScreen extends React.Component 
{
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true
    }
  }
  componentDidMount(){
    const fetch = require('node-fetch');
    fetch('http://03d77927eb6d.ngrok.io/AntrimElimChurch/backend/FilterCat.php', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
   
        // Getting the id.
        id: this.props.navigation.state.params.FlatListClickItemHolder
    })
   }).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson     
      });
    }).catch((error) => {
      console.error(error);
    });

  }


  FlatListViewItemSeparator = () => {
    return (
      <View
      style={{
        height: .5,
        width: "100%",
        backgroundColor: "#000",
      }}
    />
    );
  }

  OpenSecondActivity(id) {
    this.props.navigation.navigate("Podcats", { FlatListClickItemHolder: id});
  }

  componentDidMount() {
    this.dataSource.addEventListener('change', this.RunNotification);
  }

  RunNotification = () => {
      fetch('http://localhost:8080/api', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then(res => {
        console.log(res);
        return res.json();
      }).then(response => {
        console.log(response)
        this.data = response;
      }).catch(error =>{
        this.error = error.message || error.error;
      });
    };

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
      <View style={styles.MainContainer}>
        <FlatList style={{paddingTop: 30}}
          data={ this.state.dataSource }
          ItemSeparatorComponent = {this.FlatListItemSeparator}
          renderItem={this._renderItem}
          keyExtractor={(item, index) => index.toString()} />
      </View>
    );
  }
     
     _renderItem = ({item}) => {

      return(
          <View style={styles.MainView}>
            <View style={{flex: 1, flexDirection: 'row'}}>
              <Text style={styles.rowViewContainer} onPress={this.OpenSecondActivity.bind(this, item.id)}>{item.Name}</Text>
              {/* <Text style={styles.SermonByText}>{item.SermonBy}</Text> */}
              <Text style={styles.PodcastByText}> - {item.DateRecorded}</Text>
          </View>
          </View>
      );
    }
    
  }

I am really confused as to how to do this as I am new to react native and not that confident with php.

CodeLover
  • 166
  • 1
  • 11
  • 34
  • 2
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Dec 17 '20 at 17:10
  • I had completely forgot about this as this is old code and hasn't been updated in a while – CodeLover Dec 17 '20 at 19:20

1 Answers1

1

I recommend you to use sockets.

NPM socket.io is easy to use for front End

For your backend in PHP you can use this library https://github.com/walkor/phpsocket.io

So each time a new record has been added to your database you must use an handler to send a socket request to your client

Loic H
  • 328
  • 4
  • 12