how fix, recovery problem uid LocalStorage ReactJS/ NodeJs - node.js

I would like to explain my problem of the day.
to put you in context, I'm logging in and I'm on a page like my information or my profile.
I have a funny error, so I'm trying to recover data from. my BDD in order to correctly display the telephone number.
the 1st error is the following on my LIVE server when the page opens I have a 404 error which is displayed
and the second when I make a POSTMAN request
{
code: 'ER_BAD_FIELD_ERROR',
errno: 1054,
sqlMessage: "Unknown column 'undefined' in 'where clause'",
sqlState: '42S22',
index: 0,
sql: 'SELECT * from cartebleuuser where telephone=undefined'
}
I would like to be able to display the correct telephone which corresponds to the UID in my database
How can I fix this issue?
import React, { Component } from 'react';
import axios from 'axios'
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
userProfile: null
};
}
getUserProfile = async (telephone) => {
const res = await axios.get(
`https://joke.fr/api/cartebleuuser${telephone}`
);
this.setState({ userProfile: res.data });
console.log(res.data);
}
componentDidMount() {
const user = localStorage.getItem("authUser");
console.log(user);
if (user) {
const { id, telephone } = JSON.parse(user);
this.getUserProfile(telephone);
}
}
render() {
const { userProfile } = this.state;
return (
<div>
{userProfile ? userProfile.telephone : "No user telephone"}
</div>
)
}
}
export default Profile;
MyRoute on BDD
app.get('/api/cartebleuuser', (req, res) => {
const { telephone } = req.params;
console.log(telephone);
connection.query(`SELECT * from cartebleuuser where telephone=${telephone}`, (err, results)
=> {
if (err) {
console.log(err);
return res.status(500).send('Erreur lors de la récupération des employés');
} else {
console.log(results);
return res.json(results);
}
});
});
BDD schéma.
{
"id": 62,
"telephone": "0202020202",
"uid": "dycjibu96zgmzc0KpGAqxKiUsMu2"
}

Related

When clicking on detect a face even witout entering url the numbers are still moving up

i am currenty using the Clarifai API to detect faces, i also created that whenever i detect a face the numbers are moving up
see below imageurl image
however, when i click on detect, even without entering any url, the number still moves up, how can i prevent it from moving up when nothing is entered,
see my code below
FRONTEND code App.js
import React, { Component } from 'react';
import Particles from 'react-particles-js';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import Navigation from './components/Navigation/Navigation';
import Signin from './components/Signin/Signin';
import Register from './components/Register/Register';
import Logo from './components/Logo/Logo';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import Rank from './components/Rank/Rank';
import './App.css';
const particlesOptions = {
particles: {
number: {
value: 30,
density: {
enable: true,
value_area: 800
}
}
}
}
const initialState = {
input: '',
imageUrl: '',
box: {},
route: 'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: ''
}
}
class App extends Component {
constructor() {
super();
this.state = initialState;
}
loadUser = (data) => {
this.setState({user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}})
}
calculateFaceLocation = (data) => {
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - (clarifaiFace.right_col * width),
bottomRow: height - (clarifaiFace.bottom_row * height)
}
}
displayFaceBox = (box) => {
this.setState({box: box});
}
onInputChange = (event) => {
this.setState({input: event.target.value});
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input});
fetch('https://ancient-sea-46547.herokuapp.com/imageurl', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
input: this.state.input
})
})
.then(response => response.json())
.then(response => {
if (response) {
fetch('https://ancient-sea-46547.herokuapp.com/image', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
id: this.state.user.id
})
})
.then(response => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, { entries: count}))
})
.catch(console.log)
}
this.displayFaceBox(this.calculateFaceLocation(response))
})
.catch(err => console.log(err));
}
onRouteChange = (route) => {
if (route === 'signout') {
this.setState(initialState)
} else if (route === 'home') {
this.setState({isSignedIn: true})
}
this.setState({route: route});
}
render() {
const { isSignedIn, imageUrl, route, box } = this.state;
return (
<div className="App">
<Particles className='particles'
params={particlesOptions}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />
{ route === 'home'
? <div>
<Logo />
<Rank
name={this.state.user.name}
entries={this.state.user.entries}
/>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}
/>
<FaceRecognition box={box} imageUrl={imageUrl} />
</div>
: (
route === 'signin'
? <Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange}/>
: <Register loadUser={this.loadUser} onRouteChange={this.onRouteChange}/>
)
}
</div>
);
}
}
export default App;
BACKEND code image.js
const Clarifai = require('clarifai');
const app = new Clarifai.App({
apiKey: '378c71a79572483d9d96c7c88cb13a7a'
});
const handleApiCall = (req, res) => {
app.models
.predict(Clarifai.FACE_DETECT_MODEL, req.body.input)
.then(data => {
res.json(data);
})
.catch(err => res.status(400).json('unable to work with API'))
}
const handleImage = (req, res, db) => {
const { id } = req.body;
db('users').where('id', '=', id)
.increment('entries', 1)
.returning('entries')
.then(entries => {
res.json(entries[0].entries)
})
.catch(err => res.status(400).json('unable to get entries'))
}
module.exports = {
handleImage,
handleApiCall
}
anything i can add to prevent it?
It seems the issue is with how you handle state object, and not with the Clarifai API. For example, instead of directly modifying the state using this.state, try using this.setState(). This way, when a value in the state object changes, the component will re-render, implying that the output will change according to the new values of the detected faces.
i figured the issue,
My frontend logic woudlnt work because I'm just returning a JSON object and not assigning any status code as such. So when i receive a JSON response you cannot say if(response) because in both the cases of success and failure you get a JSON and your if condition will always be true. So instead, i just wrapped the fetch call
with an if condition saying if(this.state.input) so that you handle the case where users cannot click on a button without entering an URL

how to create poll using API with react functional component

this is my react js code and I want to connect with my node js API but I don't understand how to that ...!
import React, { useState } from "react";
import Poll from "react-polls";
// import "./styles.css";
/**
* https://stackoverflow.com/questions/65896319/react-js-class-poll-convert-into-react-hooks-poll
*/
// Declaring poll question and answers
const pollQuestion = "Youtube is the best place to learn ?";
const answers = [
{ option: "Yes", votes: 7 },
{ option: "No", votes: 2 },
{ option: "don't know", votes: 1 },
];
const Fakepolls = () => {
// Setting answers to state to reload the component with each vote
const [pollAnswers, setPollAnswers] = useState([...answers]);
// Handling user vote
// Increments the votes count of answer when the user votes
const handleVote = (voteAnswer) => {
setPollAnswers((pollAnswers) =>
pollAnswers.map((answer) =>
answer.option === voteAnswer
? {
...answer,
votes: answer.votes + 1,
}
: answer
)
);
};
return (
<div>
<Poll
noStorage
question={pollQuestion}
answers={pollAnswers}
onVote={handleVote}
/>
</div>
);
};
export default function App() {
return (
<div className="App">
<Fakepolls />
</div>
);
}
It work's fine with
// Declaring poll question and answers
const pollQuestion = "Youtube is the best place to learn ?";
const answers = [
{ option: "Yes", votes: 7 },
{ option: "No", votes: 2 },
{ option: "don't know", votes: 1 },
];
but I want to connect this poll with my API instead of Declaring it ..! this is my api- to get data -> ( router.get("/poll/:pollId", getPoll); //)
exports.getPoll = async (req, res, next) => {
try {
const { pollId } = req.params;
const polls = await Poll.findById(pollId);
if (!polls) throw new Error("no polls found");
res.status(200).json(polls);
} catch (error) {
error.status = 400;
next(error);
}
};
This is a postman image -
and this API for POST data- and my node js code -
exports.votes = async (req, res, next) => {
try {
/**
* 1. get the poll from db
* 2. check if the user already exists in any option
* 3. if user has already selected any option do nothing
* 4. if user has selected any other option remove from that option
* 5. if user does not exist in any option, insert his user id to selected option
*/
const { pollId } = req.params;
let { userId, answer } = req.body;
// get selected poll from db
const poll = await Poll.findById(pollId);
if (answer && poll) {
answer = answer.toLowerCase();
///Finf the Poll
let existingVote = null;
Object.keys(poll.options).forEach((option) => {
// loop on all options, check if the user already exists in any option
if (poll.options[option].includes(userId)) {
existingVote = option;
}
});
if (existingVote == null) {
// if there is no existing vote save it to db
try {
const push = {};
push[`options.${answer}`] = userId;
const update = await Poll.findByIdAndUpdate(
pollId,
{ $push: push },
{ upsert: true }
);
res.status(201).json(update);
} catch (err) {
error.status = 400;
next(error);
}
} else if (existingVote && existingVote.length > 0) {
// check if answer is same as previous, if yes send not modified
if (existingVote.toLowerCase() === answer.toLowerCase()) {
res.status(304).send("Response already saved");
} else {
// delete the previous response and save it in new
if (
Array.isArray(poll.options[existingVote]) &&
poll.options[existingVote].length > 0
) {
// TODO: filtering this is not returning array but 1
poll.options[existingVote] = poll.options[existingVote].filter(
(vote) => vote != userId
);
poll.options[answer] = poll.options[answer].push(userId);
const update = await Poll.findByIdAndUpdate(pollId, {
$set: { options: poll.options },
});
res.status(201).json(update);
}
}
} else {
error = {
status: 500,
message: "Something went wrong",
};
next(error);
}
} else {
error = {
status: 404,
message: "Poll not found",
};
next(error);
}
} catch (error) {
error.status = 400;
next(error);
}
};
this is a POSTMAN image using POST to store data --- >
how can I connect API with react poll
What you'd do is make a fetch() to your /api/polls endpoint inside your Fakepolls component, the URL being exactly as you show in your Postman screenshot. More info on fetch here at the MDN docs.
With the response you get from the endpoint, populate the answers array you component uses. From what I see, it would require a bit of transformation as your answer object is not quite the same as what Poll needs.
Next, upon user action, as well as updating the votes in the UI, you need to make another fetch to your vote endpoint.
Here's your component again with these adjustments. Keep in mind it's untested and the URLs are obviously not real:
import React, { useState, useEffect } from "react";
import Poll from "react-polls";
// import "./styles.css";
/**
* https://stackoverflow.com/questions/65896319/react-js-class-poll-convert-into-react-hooks-poll
*/
const Fakepolls = () => {
// Setting answers to state to reload the component with each vote
const [pollQuestion, setPollQuestion] = useState('');
const [pollAnswers, setPollAnswers] = useState([]);
// Query the actual poll info from the server
useEffect(() => {
fetch('http://your-server/api/polls/you-poll-id')
.then((response) => response.json()) //parse response as json
.then((pollObject) => {
let answerCountDictionary = Object.keys(pollObject.options)
.map(oKey => {
return {
option: oKey,
anwers: pollObject.options[oKey].length
}
}); //iterate over the 'options' properties' keys to get the names and the current votes
setPollAnswers(answerCountDictionary);
setPollQuestion(pollObject.question)
})
.catch((error) => {
console.error('Error:', error);
});
},[]) //adding empty array of dependencies to prevent multiple calls on state change
// Handling user vote
// Increments the votes count of answer when the user votes
const handleVote = (voteAnswer) => {
setPollAnswers((pollAnswers) =>
pollAnswers.map((answer) =>
answer.option === voteAnswer
? {
...answer,
votes: answer.votes + 1,
}
: answer
)
);
//also submit the backend
fetch('http://your-server/api/vote/poll-id', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
"userId": "the-logged-in-user",
"answer": voteAnswer
},
})
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
return (
<div>
<Poll
noStorage
question={pollQuestion}
answers={pollAnswers}
onVote={handleVote}
/>
</div>
);
};
export default function App() {
return (
<div className="App">
<Fakepolls />
</div>
);
}

Call my account list in render using map function in React

I don't know how to display a list of items in render(). I mostly use an array where the list is stored and get items from this array in render.
Here is my code:
constructor(props) {
super(props);
this.state = {
items: []
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
let { items } = this.state;
const token = localStorage.getItem('toktok');
fetch(`${API}/api/accounts`,{
headers :{
'authorization': `Bearer ${token}`,
}
})
.then(results => {
return results.json();
})
.then(data => {
const temp = data.result;
items = temp;
// localStorage.setItem('mymy', "fiss");
console.log(items);
console.log(items.length);
})
.catch(err => {
console.log("erroooor : ",err);
});}
and this is the render() in which the elements are called
render(){
var { items} = this.state;
{
items.length > 0 ? items.map(item => {
const {nom, prenom, email, tel} = item;
return <div className="ohayo" key={email}>
<p>{email}</p>
<p>{nom}</p>
<p>{prenom}</p>
<p>{tel}</p>
</div>
}) : "null"
}
}
It looks like all you really need to do is set your items to state after you fetch them.
.then(data => {
// localStorage.setItem('mymy', "fiss");
this.setState({ items: data.result });
})

Fetch API - How Do I Send Query From Front End to Backend?

I need to pass a search query from my front end (in React) to my back end (Express) so that my Twitter API route will grab the correct data. Here is where I'm hitting the Twitter API. I was just playing around with a req.query to check out JSON so I know that part needs to be removed.
tweets.js
var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser');
const Twit = require('twit');
const config = require('./config');
var T = new Twit(config);
/* GET users listing. */
router.get('/', function(req, res, next) {
let ticker = req.query.ticker;
T.get('search/tweets', { q: ticker })
.then(function(result) {
var tweets = result.data;
console.log(tweets);
res.send({tweets});
})
.catch(function(err) {
console.log('caught error', err.stack)
res.send({ error: err })
})
})
module.exports = router;
Also note route is set up like this in express
app.use('/tweets', tweets);
And here is my front end in React (ignoring the actual search component for now). Just confused as to how I would send a search query
import React, { Component } from 'react';
import '../App.css';
const filterData = (tweet) => {
return ((!tweet.retweeted) && !(tweet.text.includes('RT #') && ((tweet.in_reply_to_status_id) === null)));
};
class Twitter extends Component {
constructor(props) {
super(props);
this.state = {
tweets:[],
}
}
componentDidMount() {
this.getData("GOOG");
}
getData = (query) => {
fetch('/tweets?ticker='+query)
.then(res => res.json())
.then(data => data.statuses)
.then(statuses => statuses.filter(filterData))
.then(results => this.setState({tweets:results}))
}
render() {
return (
<div className="App">
<h1>Tweets About </h1>
{this.state.tweets.map(tweet =>
<div key={tweet.id}>{tweet.text}</div>
)}
</div>
);
}
}
export default Twitter;
The issue is here in this line.
Wrong one
fetch('/tweets?ticker={query)') <-- this is wrong
Correct one
const filterData = (tweet) => {
return ((!tweet.retweeted) && !(tweet.text.includes('RT #') && ((tweet.in_reply_to_status_id) === null)));
};
class Twitter extends Component {
constructor(props) {
super(props);
this.state = {
tweets:[],
}
}
componentDidMount() {
this.getData("GOOG");
}
getData = (query) => {
fetch(`http://localhost:3001/tweets?ticker=${query}`, {method: 'GET', headers: {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"}})
.then(res => res.json())
.then(data => data.statuses)
.then(statuses => statuses.filter(filterData))
.then(results => this.setState({tweets:results}))
}
renderTweets(){
if(this.state.tweets){
this.state.tweets.map(tweet =>
<div key={tweet.id}>{tweet.text}</div>
)
}
}
render() {
return (
<div className="App">
<h1>Tweets About </h1>
{this.state.tweets ? this.renderTweets(): ''}
</div>
);
}
}
export default Twitter;
Use template literals
fetch(`/tweets?ticker=${query}`)
OR
use normal string
fetch('/tweets?ticker='+query)
Check here for more details on how template literals works. Your code should be fine now.

How to use Backend Object in FrontEnd TypeScript (MEAN Stack)

Using MongoDB, express.js, angular4, node.js
A string I retrieve is well retrieved, but not the same as a full object...
account.service.ts (full, )
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
const jwtDecode = require('jwt-decode');
import { User } from '../../models/user.model';
import { AuthService } from './auth.service';
#Injectable()
export class AccountService {
constructor(private http: HttpClient,
private authService: AuthService) {}
user: any[];
currentUser() {
if(this.authService.isAuthenticated()){
const token = localStorage.getItem('token');
const decoded = jwtDecode(token);
return decoded.user;
}
};
getProfile() {
const id = this.currentUser();
return this.http.get("http://localhost:3000/user/" + id).
map(
(response: Response) => {
const data = response.json();
return data;
}
)
.catch(
(error: Response) => {
console.log(error);
return Observable.throw(error.json());
}
)
}
user-profile.component.ts
export class UserProfileComponent implements OnInit {
id: string;
user: any;
constructor(private account: AccountService) {}
ngOnInit() {
this.id = this.account.currentUser();
this.user = this.account.getProfile()
.subscribe(user => {
this.user = user;
return this.user;
});
}
logUser() {
console.log(this.id);
console.log(this.user);
}
}
user-profile.component.html
<p>{{user}}</p>
<p>User with ID {{id}} Loaded</p>
<a (click)="logUser()">Log User Test</a>
HTML file shows:
[object Object]
User with ID 59ca916323aae527b8ec7fa2 Loaded
What I get from clicking "log User" link is the retrieved ID string and the user object:
59ca916323aae527b8ec7fa2
[{...}] //clicking this reveals all of the object's details.
But I can't make that step of getting those details and presenting them in the HTML as I successfully managed with the ID... I mean, {{user.anything}} doesn't fetch the user's data as it should
May I have some assistance?
Change your getProfile() to,
getProfile() {
const id = this.currentUser();
return this.http.get("http://localhost:3000/user/" + id).
map(
(response) => response.json()
)
.catch(
(error: Response) => {
console.log(error);
return Observable.throw(error.json());
}
)
}
Also, in ngOnInit() change this one,
this.user = this.account.getProfile()
.subscribe((user) => {
this.user = user;
});
See if it gives you the right output.
EDIT
Change this one,
this.user = this.account.getProfile()
.subscribe((user) => {
this.user = JSON.parse(JSON.stringify(user));
});
EDIT-2
this.user = this.account.getProfile()
.subscribe((user) => {
this.user = JSON.stringify(user);
this.userObj = JSON.parse(JSON.stringify(user));
// also try, this.userObj = user; if above line didn't work
});
Define another property in component as ,
userObj: any;
Refer to the object in template as this
{{ userObj[0]?.email }}

Resources