Child component doesn't receive props passed - php

So i'm building a QRcode scanner app.
When I scan a barcode, I want another modal to appear but I want to data (decoded from barcode) to be passed to my child Component which is ResponseModal.
here is my code
QrScanner.js
import { useHistory } from "react-router-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";
import React, { useEffect, useState} from "react";
import axios from 'axios';
import ResponseModal from './ResponseModal';
const QrScanner = () => {
const [data, setData ] = useState('');
const [flag, setFlag] = useState(false);
const history = useHistory();
useEffect(() => {
if(data === '') {
return;
}
if (Number.isInteger(parseInt(data))) { // barcode scanned
axios.get('/some/endpoint/code/' + data)
.then(res => {
if (res.data != false) {
setFlag(true);
} else{
setData('Sorry, Wrong barcode!');
}
})
}
})
return (
<>
<BarcodeScannerComponent
width={500}
height={500}
onUpdate={(err, result) => {
if (result) {
setData(result.text);
}
}}
/>
<p className="modal-result-show">{data}</p> <---- this updates fine when barcode is scanned
<ResponseModal open={flag} data={data}/> <---- this is empty, why?
</>
);
}
export default QrScanner
And here is my ResponseModal:
import 'react-responsive-modal/styles.css';
import Modal from 'react-responsive-modal';
import React, {useEffect, useState} from "react";
const ResponseModal = (flag, data) => {
const [open, setOpen] = useState(false);
const onCloseModal = () => setOpen(false);
console.log(data); <----- empty
useEffect(() => {
if(flag.open === true) {
setOpen(true);
flag.open = false;
}
})
return (
<>
<Modal open={open} onClose={onCloseModal}>
<div className="qr-modal-header-stock">
<h5>Enter fulfillment stock</h5>
<form action="/some/another/endpoint/save" method="POST">
<input type="hidden" name="ean" value={data} /> <--- empty
<input type="number" name="product_stock" class="form-control"/> <br />
<input type="submit" class="btn btn-primary form-control"/>
</form>
</div>
</Modal>
</ >
);
}
export default ResponseModal
My question is, why am I not receing the data in my ResponseModal? I thought whenever {data} updates, everything that uses it also re-renders or being passed. What am I missing? I need {data} to do some logic with it on my backend side.

You are using props wrong way. props is one object, just update like this.
const ResponseModal = (props) => {
const {flag, data} = props;
}

Related

How to display the users_ID on the screen with react native

I made login with PHP and React Native but now I want to display the ID of the user that's logged in. The ID should be showed on the screen that appears when the user is logged in.
I tried several things but I think the way I request the props is wrong. Because the page where I want to show never requests the data that is started in the previous page.
This is the login screen:
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import * as Expo from 'expo';
export default class App extends React.Component {
state = {
username: '',
password: '',
response: '',
users_ID: '',
};
handleusers_usernameChange = (users_username) => {
this.setState({ users_username });
};
handleusers_passwordChange = (users_password) => {
this.setState({ users_password });
};
handleLoginPress = async () => {
const { users_username, users_password } = this.state;
try {
let response = await fetch('http://IP/CodingApp/login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
users_username,
users_password,
}),
});
let responseJson = await response.json();
console.log(responseJson);
if (responseJson.loggedin) {
this.props.setLoggedIn(true, responseJson.users_ID);
this.setState({ users_ID: responseJson.users_ID });
} else {
this.setState({ response: 'tekst kwam niet overeen' });
}
} catch (error) {
console.error(error);
}
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
value={this.state.users_username}
onChangeText={this.handleusers_usernameChange}
placeholder="users_username"
/>
<TextInput
style={styles.input}
value={this.state.users_password}
onChangeText={this.handleusers_passwordChange}
placeholder="users_password"
secureTextEntry
/>
<Button title="Login" onPress={this.handleLoginPress} />
<Text>{this.state.response}</Text>
</View>
);
}
}
And this is the screen that appears after the user is logged in:
import React from 'react';
import { View, Text } from 'react-native';
const EditFamily = (props) => {
return (
<View>
<Text>Your user ID is: {props.users_ID}</Text>
</View>
);
};
export default EditFamily;
Read about redux, which is a state management tool, you can save id whenever or wherever you go and use it everywhere.
https://redux.js.org/introduction/getting-started

How to receive data using file_get_contents?

Here I am trying to send my js object from react app to php file with the help of axios but I am not getting my data there instead it is returning null and connection is made successfully between react and php beacuse if I echo something in php it works but when I try to print object data it returns null so someone can please help me
import { useState } from "react";
import axios from "axios";
const App = () => {
const [username, setUsername] = useState();
const [password, setPassword] = useState();
let [input, setInput] = useState({ username: "", password: "" });
const nameChangeHandler = (e) => {
setUsername(e.target.value);
};
const passwordChangeHandler = (e) => {
setPassword(e.target.value);
};
const formHandler = (e) => {
e.preventDefault();
setInput(((input.username = username), (input.password = password)));
JSON.stringify(input);
axios.post("http://localhost:80/api/index.php", input);
console.log(input);
};
return (
<form onSubmit={formHandler}>
<label>Username</label>
<input type="text" onChange={nameChangeHandler} />
<label>Password</label>
<input type="password" onChange={passwordChangeHandler} />
<input type="submit" />
</form>
);
};
export default App;
PHP:
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
$data = json_decode( file_get_contents("php://input"));
print_r($data);
var_dump($data);
?>

php cannot read FormData that contains multiple files

In php, I cannot access the uploaded files in $_FILES instead they appear in $_POST["imgs"] as [object File] without any properties like name.
How can I get those files accessed in $_FILES?
import React, { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import axios from 'axios'
const imgAjaxUploader = axios.create({
baseURL: 'http://localhost',
timeout: 1000,
headers: { 'Content-Type': 'mulipart/form-data' }
});
export default function ImgDropzone() {
const onDrop = useCallback(acceptedFiles => {
const formData = new FormData()
formData.append('imgs', acceptedFiles)
try {
imgAjaxUploader.post('/store/admin/imgHandler.php', formData, {
headers: {
'Content-Type': 'mulipart/form-data'
}
}).then(data =>
console.log(data)
).catch(err => {
console.log(err)
return null
})
} catch (err) {
alert(err)
}
}, [])
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop: onDrop, accept: 'image/jpeg, image/png' })
return (
<div {...getRootProps()} style={{ display: "inline-block" }}>
<input {...getInputProps()} />
{
isDragActive ?
<p>Drop the files here ...</p> :
<p>Drag 'n' drop some files here, or click to select files</p>
}
</div>
)
}
I found the solution. Multiple files need to be appended to the same name with a trailing [], in order to be compatible with PHP:
acceptedFiles.forEach(file => {
formData.append('imgs[]', file)
})
resource example 3

Laravel Webrtc video chat with react and pusher

I created a web app for video using Laravel, pusher and react js but now problem is that I was following the tutorial I don't know about the react but I'm good in Laravel.
Now I want to add a function where I can send email to a user so he can join me in video chat, right now it is working on click functions where react take an id and send the request to the client channel.
here is my react code.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import MediaHandler from '../MediaHandler';
import Pusher from 'pusher-js';
import Peer from 'simple-peer';
const APP_KEY = 'removed-app-key';
export default class App extends Component {
constructor() {
super();
this.state = {
hasMedia: false,
otherUserId: null
};
this.user = window.user;
this.user.stream = null;
this.peers = {};
this.mediaHandler = new MediaHandler();
this.setupPusher();
this.callTo = this.callTo.bind(this);
this.setupPusher = this.setupPusher.bind(this);
this.startPeer = this.startPeer.bind(this);
}
componentWillMount() {
this.mediaHandler.getPermissions()
.then((stream) => {
this.setState({hasMedia: true});
this.user.stream = stream;
try {
this.myVideo.srcObject = stream;
} catch (e) {
this.myVideo.src = URL.createObjectURL(stream);
}
this.myVideo.play();
})
}
setupPusher() {
Pusher.logToConsole=true;
this.pusher = new Pusher(APP_KEY, {
authEndpoint: '/pusher/auth',
cluster: 'ap2',
auth: {
params: this.user.id,
headers: {
'X-CSRF-Token': window.csrfToken
}
}
});
this.channel = this.pusher.subscribe('presence-video-channel');
this.channel.bind(`client-signal-${this.user.id}`, (signal) => {
let peer = this.peers[signal.userId];
// if peer is not already exists, we got an incoming call
if(peer === undefined) {
this.setState({otherUserId: signal.userId});
peer = this.startPeer(signal.userId, false);
}
peer.signal(signal.data);
});
}
startPeer(userId, initiator = true) {
const peer = new Peer({
initiator,
stream: this.user.stream,
trickle: false
});
peer.on('signal', (data) => {
this.channel.trigger(`client-signal-${userId}`, {
type: 'signal',
userId: this.user.id,
userName:this.user.name,
data: data
});
});
peer.on('stream', (stream) => {
try {
this.userVideo.srcObject = stream;
} catch (e) {
this.userVideo.src = URL.createObjectURL(stream);
}
this.userVideo.play();
});
peer.on('close', () => {
let peer = this.peers[userId];
if(peer !== undefined) {
peer.destroy();
}
this.peers[userId] = undefined;
});
return peer;
}
callTo(userId) {
this.peers[userId] = this.startPeer(userId);
}
render() {
return (
<div className="App">
{[1,2,3,4].map((userId) => {
return this.user.id !== userId ? <button key={userId} onClick={() => this.callTo(userId)}>Call {name}</button> : null;
})}
<div className="video-container">
<video className="my-video" ref={(ref) => {this.myVideo = ref;}}></video>
<video className="user-video" ref={(ref) => {this.userVideo = ref;}}></video>
</div>
</div>
);
}
}
if (document.getElementById('app')) {
ReactDOM.render(<App />, document.getElementById('app'));
}
Here is my pusher function.
public function authenticate(Request $request){
$socketId= $request->socket_id;
$channelName= $request->channel_name;
$pusher = new Pusher('APP_KEY', 'APP_SECRET','APP_ID',['cluster'=> 'ap2','forceTLS'=>true]);
$presence_data = ['name' => auth()->user()->name];
$key = $pusher->presence_auth($channelName, $socketId, auth()->id(), $presence_data);
return response($key);
}
My head script
!-- Scripts -->
#if(auth()->user())
<script>
window.user = {
id:{{auth()->id()}},
name:"{{auth()->user()->first_name}}"
};
window.csrfToken = "{{ csrf_token() }}";
</script>
#endif
The simple thing I want to create a room where I can send email to user to join me one-to-one video chat.
I'm searching this from last night but no good result till now

angular 8 elements disappearing after post request

I'm a beginner in angular , i was trying to establish a connection with database using php as backend programming language , it was working fine and the elements were showing from database but when i inserted them to the database , it does work and they are inserted to the database but my elements disappear when the form is submitted and when the form is submitted again they flash for seconds .
MY HTML CODE
<form (submit)="loginUser($event)">
<input type="text" placeholder="User name" id="name" >
<input type="password" placeholder="password" id="pass">
<button type="submit" >Log in</button>
{{name}}
</form>
<ul *ngFor="let item of datas ">
<li>{{item.name}} {{item.pass}}</li>
</ul>
MY LOGIN.COMPONENT FILE
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { iEmployee } from '../../empolyee';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor( private Auth:AuthService) { }
public datas;
ngOnInit() {
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
loginUser(event: { preventDefault: () => void; target: any; }){
event.preventDefault();
const target = event.target;
const name=target.querySelector('#name').value;
const pass=target.querySelector('#pass').value;
this.Auth.createuser(name,pass).subscribe(data=>this.datas=data);
this.Auth.getUserDetail().subscribe(data=> this.datas=data);
}
}
MY AUTH.SERVICE FILE
import { Injectable } from '#angular/core';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { iEmployee } from '../empolyee';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http:HttpClient) { }
private url : string='http://localhost:81/example/Angular/php/display.php';
private url2:string='http://localhost:81/example/Angular/php/addNew.php';
getUserDetail() {
return this.http.get(this.url)
}
createuser(name , pass) {
return this.http.post(this.url2,{name,pass},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
}
}
MY ADDNEW.PHP FILE
<?php
header('Access-Control-Allow-Origin: *');
include 'connection.php';
$data = json_decode(file_get_contents("php://input"),true);
$name= $data['name'];
$pass= $data['pass'];
$sql="insert into test(name,pass) values ('$name','$pass')";
$result = mysqli_query($con, $sql);
?>

Categories