Using Custom Claims in React Firebase Hooks to access specific database Ref - reactjs

I'm pretty new to React Hooks and I'm trying to figure out how to use react-firebase-hooks with custom claims.
My firebase Realtime Database is structured like so :
groups
--- key1
------- clients
------- info
--- key2
------- clients
------- info
Each user has a custom claim named "group" carrying the group Key.
I have this code so far but it's throwing me a:
Uncaught TypeError: Cannot read property 'hasCancelCallback' of undefined
at ChildEventRegistration.createCancelEvent"
function ClientList() {
const [firebaseUser, loadingFirebaseUser] = useAuthState(auth);
const [userGroup, setUserGroup] = useState();
useEffect(() => {
const fetchClaims = async () => {
const {
claims: { group },
} = await firebaseUser.getIdTokenResult();
setUserGroup(group);
};
if (firebaseUser) fetchClaims();
}, [firebase.database(), firebaseUser]);
const [snapshots, loading, error] = useList(
firebase.database().ref(`groups/${userGroup}/clients`)
);
return (
<div>
<h2>List of Clients</h2>
{userGroup && <p>{userGroup}</p>}
{error && <strong>Error: {error}</strong>}
{loading && <span>List: Loading...</span>}
{!loading && snapshots && (
<ul>
{snapshots.map((v) => (
<li key={v.key}>
{v.key}}
</li>
))}
</ul>
)}
</div>
);
}
I might be missing something very obvious here.
Here's a full stack trace of the error :
overrideMethod # react_devtools_backend.js:2557
printWarnings # vendors~main.chunk.js:36207
handleWarnings # vendors~main.chunk.js:36212
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage # vendors~main.chunk.js:36277
vendors~main.chunk.js:28144 Uncaught TypeError: Cannot read property 'hasCancelCallback' of undefined
at ChildEventRegistration.createCancelEvent (vendors~main.chunk.js:28144)
at vendors~main.chunk.js:23797
at Array.forEach (<anonymous>)
at viewRemoveEventRegistration (vendors~main.chunk.js:23796)
at syncPointRemoveEventRegistration (vendors~main.chunk.js:24047)
at syncTreeRemoveEventRegistration (vendors~main.chunk.js:24417)
at onComplete (vendors~main.chunk.js:24743)
at Object.onComplete (vendors~main.chunk.js:25874)
at vendors~main.chunk.js:16786
at PersistentConnection.onDataMessage_ (vendors~main.chunk.js:17069)
at Connection.onDataMessage_ (vendors~main.chunk.js:15624)
at Connection.onPrimaryMessageReceived_ (vendors~main.chunk.js:15617)
at WebSocketConnection.onMessage (vendors~main.chunk.js:15497)
at WebSocketConnection.appendFrame_ (vendors~main.chunk.js:15050)
at WebSocketConnection.handleIncomingFrame (vendors~main.chunk.js:15108)
at WebSocket.mySock.onmessage (vendors~main.chunk.js:14984)
ChildEventRegistration.createCancelEvent # vendors~main.chunk.js:28144
(anonymous) # vendors~main.chunk.js:23797
viewRemoveEventRegistration # vendors~main.chunk.js:23796
syncPointRemoveEventRegistration # vendors~main.chunk.js:24047
syncTreeRemoveEventRegistration # vendors~main.chunk.js:24417
onComplete # vendors~main.chunk.js:24743
(anonymous) # vendors~main.chunk.js:25874
(anonymous) # vendors~main.chunk.js:16786
PersistentConnection.onDataMessage_ # vendors~main.chunk.js:17069
Connection.onDataMessage_ # vendors~main.chunk.js:15624
Connection.onPrimaryMessageReceived_ # vendors~main.chunk.js:15617
(anonymous) # vendors~main.chunk.js:15497
WebSocketConnection.appendFrame_ # vendors~main.chunk.js:15050
WebSocketConnection.handleIncomingFrame # vendors~main.chunk.js:15108
mySock.onmessage # vendors~main.chunk.js:14984

Related

Appropriate loader to handle this file type

When doing an npm update with npm audit fix --force I started getting this build output:
Module parse failed: Unexpected token (20:40) You may need an
appropriate loader to handle this file type. | var seeLocation =
function seeLocation(lat, long) { | var link =
"https://www.google.com/maps/search/?api=1&query=" + lat + "%2C" +
long;
var win = window.open(link, '_blank')?.focus(); | }; |
This is the code:
const seeLocation = ( lat:any, long:any) =>{
const link="https://www.google.com/maps/search/?api=1&query="+lat+"%2C"+long
const win= window.open( link, '_blank')?.focus();
}
What does it means: You may need an appropriate loader to handle this file type.
This is how I call the function:
<IonCol id="ioncol-homeclient" onClick={() => seeLocation(props.data.lat, props.data.long) } >
<IonRow id="ionrow-homecliente">
<IonIcon icon={location} /> </IonRow>
<IonRow id="ionrow-homeclient"><small>SEE LOCATION</small></IonRow>
</IonCol>

Unable to delete a postgreSQL row that has a LEFT JOIN attached

I have created a database using PostgreSQL. I have used LEFT JOIN to join a comments table to a reviews table. The frontend is created using React. I can only delete a review if it has 0 comments, if there are any comments on the review when I try to delete it a 500 internal server error throws. I was sure the LEFT JOIN would delete a review with or without comments, so not sure why this isn't working?
Any suggestions are appreciated, thank you.
https://nc-games-kirsty-richmond.netlify.app
// seed.js file
// Create Reviews Table //
const seed = async (data) => {
const { categoryData, commentData, reviewData, userData } = data;
await db.query(`DROP TABLE IF EXISTS comments, reviews, users, categories;`);
await db.query(`
CREATE TABLE reviews (
review_id SERIAL PRIMARY KEY,
title VARCHAR(75) NOT NULL,
designer VARCHAR(55) NOT NULL,
owner VARCHAR(180) REFERENCES users(username),
review_img_url VARCHAR(500) DEFAULT
'https://images.pexels.com/photos/163064/play-stone-network-networked-interactive-163064.jpeg',
review_body VARCHAR(1000) NOT NULL,
category VARCHAR(75) REFERENCES categories(slug),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
votes INT DEFAULT 0
);
`);
// Create Comments Table //
await db.query(`
CREATE TABLE comments (
comment_id SERIAL PRIMARY KEY,
body VARCHAR(1000) NOT NULL,
votes INT DEFAULT 0,
author VARCHAR(75) REFERENCES users(username) NOT NULL,
review_id INT REFERENCES reviews(review_id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
// review-models.js
exports.selectReviewById = async (review_id) => {
const review = await db.query(
`SELECT reviews.*, COUNT(comment_id)
AS comment_count
FROM reviews
LEFT JOIN comments
ON comments.review_id = reviews.review_id
WHERE reviews.review_id = $1
GROUP BY reviews.review_id;`,
[review_id]
);
return review.rows[0];
};
exports.removeReview = async (review_id) => {
removeComment();
const review = await db.query(
`DELETE FROM reviews
WHERE review_id = $1;`,
[review_id]
);
return review.rows[0];
};
Errors in console:
DELETE http://be-nc-games-app.herokuapp.com/api/reviews/114 500 (Internal Server Error)
dispatchXhrRequest # xhr.js:210
xhrAdapter # xhr.js:15
dispatchRequest # dispatchRequest.js:58
request # Axios.js:112
Axios.<computed> # Axios.js:136
wrap # bind.js:9
deleteReview # api.js:116
handleDelete # ReviewCard.jsx:55
onClick # ReviewCard.jsx:77
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4070
executeDispatch # react-dom.development.js:8243
processDispatchQueueItemsInOrder # react-dom.development.js:8275
processDispatchQueue # react-dom.development.js:8288
dispatchEventsForPlugins # react-dom.development.js:8299
(anonymous) # react-dom.development.js:8508
batchedEventUpdates$1 # react-dom.development.js:22396
batchedEventUpdates # react-dom.development.js:3745
dispatchEventForPluginEventSystem # react-dom.development.js:8507
attemptToDispatchEvent # react-dom.development.js:6005
dispatchEvent # react-dom.development.js:5924
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
discreteUpdates$1 # react-dom.development.js:22413
discreteUpdates # react-dom.development.js:3756
dispatchDiscreteEvent # react-dom.development.js:5889
Uncaught (in promise) Error: Request failed with status code 500
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)
createError # createError.js:16
settle # settle.js:17
onloadend # xhr.js:66
Promise.then (async)
handleDelete # ReviewCard.jsx:55
onClick # ReviewCard.jsx:77
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4070
executeDispatch # react-dom.development.js:8243
processDispatchQueueItemsInOrder # react-dom.development.js:8275
processDispatchQueue # react-dom.development.js:8288
dispatchEventsForPlugins # react-dom.development.js:8299
(anonymous) # react-dom.development.js:8508
batchedEventUpdates$1 # react-dom.development.js:22396
batchedEventUpdates # react-dom.development.js:3745
dispatchEventForPluginEventSystem # react-dom.development.js:8507
attemptToDispatchEvent # react-dom.development.js:6005
dispatchEvent # react-dom.development.js:5924
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
discreteUpdates$1 # react-dom.development.js:22413
discreteUpdates # react-dom.development.js:3756
dispatchDiscreteEvent # react-dom.development.js:5889
If you can delete only records that are not commented.
delete from reviews where id in (
select a.id
from reviews rv
left join comments cm on rv.id = cm.rev_id
where cm.id is null
)
Left join will be select all records. But if reviews are not commented these records showed as NULL. So adding the CM.ID IS NULL condition will filter only no comments records. After then using the subquery we can delete needed records.

GET API showing KeyError in browser, but working in Postman

I have encountered a strange problem where the GET API that I created was working fine in Postman, but not working at that specific URL when entered in the browser.
Here is what the input and output should look like as shown successfully in Postman: Trying API in Postman
Here is what the error is showing on my browser: Error in browser
I am also getting this error in React about CORS headers even though I have added in code to try to handle that issue: Error in React about CORS
Here is the code in settings.py in Django:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Prediction',
'rest_framework',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Here is the code in local_settings.py in Django:
#########################################
## IMPORT LOCAL SETTINGS ##
#########################################
try:
from .local_settings import *
except ImportError:
pass
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
#################################################################
## (CORS) Cross-Origin Resource Sharing Settings ##
#################################################################
CORS_ORIGIN_ALLOW_ALL = True
I also tried adding this code in index.js in React to handle the CORS headers problem but it didn't work:
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/jokes/random', (req, res) => {
request({
url: 'https://joke-api-strict-cors.appspot.com/jokes/random'
},
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({
type: 'error',
message: err.message
});
}
res.json(JSON.parse(body));
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
Here is the code in App.js in React:
import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
import axios from 'axios';
function App() {
const [json_response1, set_json_response1] = useState("1st algorithm - List of similar events");
function request_json_response() {
axios.get('http://127.0.0.1:8000/api/get_events_1st_alg', {
data: {
"ID": "User_ID1"
}
}).then(function (response) {
// handle success
set_json_response1(response);
});
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
{json_response1}
</p>
<button onClick={request_json_response}>
Generate events for user
</button>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Here is the code in views.py in Django:
class get_events_1st_alg(APIView):
def get(self, request, format=None):
"""
data = request.data
banana_dictionary = {'banana':17}
return Response(banana_dictionary, status=status.HTTP_201_CREATED)
"""
import pandas as pd
import numpy as np
import psycopg2
import sqlalchemy
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import pairwise_distances
import requests
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:postgres#localhost/postgres')
# pd.read_sql_query('''SELECT * FROM arts_user_interaction LIMIT 5;''', engine)
events = pd.read_sql_query('''SELECT * FROM arts_event;''', engine)
Ratings = pd.read_sql_query('''SELECT * FROM arts_user_interaction;''', engine)
Mean = Ratings.groupby(by="User_ID", as_index = False)['User Rating'].mean()
Rating_avg = pd.merge(Ratings, Mean, on = "User_ID")
Rating_avg['adg_rating']=Rating_avg['User Rating_x']-Rating_avg['User Rating_y']
check = pd.pivot_table(Rating_avg,values='User Rating_x',index='User_ID',columns='Event_ID')
final = pd.pivot_table(Rating_avg,values='adg_rating',index='User_ID',columns='Event_ID')
final_event = final.fillna(final.mean(axis=0))
final_user = final.apply(lambda row: row.fillna(row.mean()), axis=1)
cosine = cosine_similarity(final_event)
np.fill_diagonal(cosine, 0 )
similarity_with_event =pd.DataFrame(cosine,index=final_event.index)
similarity_with_event.columns=final_user.index
def find_n_neighbours(df,n):
order = np.argsort(df.values, axis=1)[:, :n]
df = df.apply(lambda x: pd.Series(x.sort_values(ascending=False)
.iloc[:n].index,
index=['top{}'.format(i) for i in range(1, n+1)]), axis=1)
return df
sim_user_30_e = find_n_neighbours(similarity_with_event,30)
def get_user_similar_events( user1, user2 ):
common_events = Rating_avg[Rating_avg.User_ID == user1].merge(
Rating_avg[Rating_avg.User_ID == user2],
on = "Event_ID",
how = "inner" )
return common_events.merge(events, on ='Event_ID')
a = get_user_similar_events('User_ID10','User_ID220')
a = a.reindex(columns= ['User Rating_x_x','User Rating_x_y','Name'])
Rating_avg = Rating_avg.astype({"Event_ID": str})
Movie_user = Rating_avg.groupby(by = 'User_ID')['Event_ID'].apply(lambda x:','.join(x))
def User_item_score1(user):
Movie_seen_by_user = check.columns[check[check.index==user].notna().any()].tolist()
a = sim_user_30_e[sim_user_30_e.index==user].values
b = a.squeeze().tolist()
d = Movie_user[Movie_user.index.isin(b)]
l = ','.join(d.values)
Movie_seen_by_similar_users = l.split(',')
Movies_under_consideration = list(set(Movie_seen_by_similar_users)-set(list(map(str, Movie_seen_by_user))))
Movies_under_consideration = list(map(str, Movies_under_consideration))
score = []
for item in Movies_under_consideration:
c = final_event.loc[:,item]
d = c[c.index.isin(b)]
f = d[d.notnull()]
avg_user = Mean.loc[Mean['User_ID'] == user,'User Rating'].values[0]
index = f.index.values.squeeze().tolist()
corr = similarity_with_event.loc[user,index]
fin = pd.concat([f, corr], axis=1)
fin.columns = ['adg_score','correlation']
fin['score']=fin.apply(lambda x:x['adg_score'] * x['correlation'],axis=1)
nume = fin['score'].sum()
deno = fin['correlation'].sum()
final_score = avg_user + (nume/deno)
score.append(final_score)
data = pd.DataFrame({'Event_ID':Movies_under_consideration,'score':score})
top_5_recommendation = data.sort_values(by='score',ascending=False).head(5)
Movie_Name = top_5_recommendation.merge(events, how='inner', on='Event_ID')
Movie_Names = Movie_Name.Name.values.tolist()
return Movie_Names
# user = input("Enter the user id to whom you want to recommend : ")
data = request.data
user = ""
for i, v in data.items():
user = str(v)
predicted_movies = User_item_score1(user)
return Response(predicted_movies, status=status.HTTP_201_CREATED)
I really don't know what I am doing as I am just following a bunch of tutorials online so I would love it if anyone can help with resolving the API issue in the browser and the React issue with CORS in the browser as well. Thank you so much!
The problem is that GET request shouldn't have body (it is not specified/supported by axios). See this issue in axios repository: link.
Please do a change from data to params:
axios.get('http://127.0.0.1:8000/api/get_events_1st_alg', { params: { "ID":"User_ID1"}})
And access it in DRF like:
user = request.query_params.get("ID")
Your CORS config is OK.

Send a POST request from React Component to Spring Boot Controller

So I have a React component called UpdateJobComponent. From here the user can either update a job or create a job (depending on the button they clicked in the previous component). The update of a job works fine however when I try to create a job i get the following errors:
Errors
Put http://localhost:8080/jobs/-1 500
Uncaught (in promise) Error: Request failed with status code 500
at createError
It tells me it's a PUT request and not a POST. However I thought I have it said up properly to match the the createJob PostMapping Controller. Below is the UpdateJobComponent code as well as the service files and also the Controller as well as the JobDataService.
I'm quite sure that the updateJob method in my JobController is receiving the POST and that's why I'm getting the problem but I can't figure out how to make the createJob in the JobController get it.
If you want to see anymore code just let me know, I tried to trim it as much as possible so not to take too long to look over! I'd really appreciate any help you can offer!
UpdateJobComponent
// imports
class UpdateJobComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
employer: this.props.match.employer,
description: ''
}
// bind methods
}
componentDidMount() {
if (this.state.id == -1) {
console.log("Not mounting")
return;
}
console.log(this.state.id)
console.log("mounting")
let userName = AuthenticationService.getLoggedUser()
JobDataService.retrieveJob(userName, this.state.id)
.then(response => this.setState({
description: response.data.description,
employer: response.data.employer,
jobTitle: response.data.jobTitle
}))
}
// Error handling for form
validate(values) {
let errors = {} // add validation for every field!!!!!!
if (!values.description) {
errors.description = 'Enter a description'
} else if (values.description.length < 5) {
errors.description = 'Description must be at least 5 characters long'
}
return errors
}
// When save is clicked
onSubmit(values) {
// let employer = this.state.employer
// let id = this.state.id
// let jobTitle = this.state.jobTitle
let job = {
id: this.state.id,
employer: values.employer,
jobTitle: values.jobTitle,
description: values.description
}
if (this.state.id === -1) {
JobDataService.createJob(job)
.then(() => this.props.history.push('/jobs'))
} else {
JobDataService.updateJob(job.jobTitle, job.employer, this.state.id, job)
.then(() => this.props.history.push('/jobs'))
}
}
render() {
let { description, employer, jobTitle } = this.state
return (
<div>
<h3>Update {this.state.employer}'s {this.state.jobTitle} Job</h3>
<div className="container">
<Formik
initialValues={{description: description, employer: employer, jobTitle: jobTitle}}
onSubmit={this.onSubmit}
validateOnChange={false}
validateOnBlur={false}
validate={this.validate}
enableReinitialize={true}
>
{
(props) => (
<Form>
// Formik form, removed to make post smaller...
<div className="btn-group mr-2" role="group" aria-label="First group">
<button className="btn btn-success" type="submit">Save</button>
</div>
JobDataService
// imports
const API_URL = 'http://localhost:8080'
const GET_ALL_JOBS_URL = `${API_URL}/jobs/`
updateJob(jobTitle, employer, id, job) {
return axios.put(`${GET_ALL_JOBS_URL}${id}`, job);
}
createJob(job) {
return axios.post(`${GET_ALL_JOBS_URL}`, job);
}
JobController
#Autowired
private JobService jobService;
#PostMapping("/jobs/")
public ResponseEntity<Job> createJob(#RequestBody Job job) {
Job createdJob = jobService.createJob(job);
java.net.URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(createdJob.getId())
.toUri();
return ResponseEntity.created(uri).build();
}
#PutMapping("/jobs/{id}")
public ResponseEntity<Job> updateJob(#PathVariable long id, #RequestBody Job job) {
job.setId(id);
return ResponseEntity.ok().body(this.jobService.updateJob(job));
}
// Other get and delete methods
JobService
public Job createJob(Job job) {
if(job.getId() == -1 || job.getId() == 0) {
job.setId(++idCounter);
jobRepository.insert(job);
}
return jobRepository.save(job);
}
public Job updateJob(Job job) {
Optional < Job > jobDb = this.jobRepository.findById(job.getId());
if (jobDb.isPresent()) {
Job jobUpdate = jobDb.get();
jobUpdate.setId(job.getId());
jobUpdate.setEmployer(job.getEmployer());
jobUpdate.setJobTitle(job.getJobTitle());
jobUpdate.setDescription(job.getDescription());
jobRepository.save(jobUpdate);
return jobUpdate;
} else {
throw new ResourceNotFoundException("Record not found with id : " + job.getId());
}
}
// Other methods
Edit
Full error message:
PUT http://localhost:8080/jobs/-1 500
dispatchXhrRequest # 1.chunk.js:561
xhrAdapter # 1.chunk.js:411
dispatchRequest # 1.chunk.js:994
Promise.then (async)
request # 1.chunk.js:807
Axios.<computed> # 1.chunk.js:831
wrap # 1.chunk.js:1308
updateJob # main.chunk.js:1428
onSubmit # main.chunk.js:955
(anonymous) # 1.chunk.js:4699
(anonymous) # 1.chunk.js:5014
(anonymous) # 1.chunk.js:4709
Promise.then (async)
(anonymous) # 1.chunk.js:4705
(anonymous) # 1.chunk.js:5014
(anonymous) # 1.chunk.js:4750
(anonymous) # 1.chunk.js:5014
callCallback # 1.chunk.js:16321
invokeGuardedCallbackDev # 1.chunk.js:16370
invokeGuardedCallback # 1.chunk.js:16423
invokeGuardedCallbackAndCatchFirstError # 1.chunk.js:16438
executeDispatch # 1.chunk.js:16569
executeDispatchesInOrder # 1.chunk.js:16594
executeDispatchesAndRelease # 1.chunk.js:16697
executeDispatchesAndReleaseTopLevel # 1.chunk.js:16706
forEachAccumulated # 1.chunk.js:16678
runEventsInBatch # 1.chunk.js:16723
runExtractedPluginEventsInBatch # 1.chunk.js:16865
handleTopLevel # 1.chunk.js:21818
batchedEventUpdates$1 # 1.chunk.js:40326
batchedEventUpdates # 1.chunk.js:17401
dispatchEventForPluginEventSystem # 1.chunk.js:21914
attemptToDispatchEvent # 1.chunk.js:22031
dispatchEvent # 1.chunk.js:21934
unstable_runWithPriority # 1.chunk.js:51411
runWithPriority$2 # 1.chunk.js:28193
discreteUpdates$1 # 1.chunk.js:40343
discreteUpdates # 1.chunk.js:17426
dispatchDiscreteEvent # 1.chunk.js:21901
I just added an if statement in the updateJob method to check if the id was -1. It's far from pretty and will need to be fixed again but wll do for now. Thanks for your time Code-Apprentice!

Uncaught (in promise) Error while opening and doing transaction on private ethereum blockchain using web3 and go-ethereum

I am trying to integrate a react app with go-ethereum using web3js.
an event Onsubmit will do the following:
1. Create an account.
2. Open the account.
3. Approve a smart contract with the created account.
Here is my code
import React, { Component } from 'react';
import './App.css';
import web3 from './web3';
....
class App extends Component {
constructor(props){
super(props);
this.state = {requester : '', receiver:'', balance: '', message:''};
}
async componentDidMount(){
const requester = await auth.methods.requester().call();
const receiver = await auth.methods.receiver().call();
const approvers = await auth.methods.approvers(0).call();
const balance = await web3.eth.getBalance(auth.options.address);
this.setState({requester,receiver,balance});
}
onSubmit = async (event)=>{
event.preventDefault();
console.log('Approving the smart contract ..... Mining in process ! ');
var pass = "xxxxxxx"
var newaccount = web3.eth.personal.newAccount(pass);
var promise1 = Promise.resolve(newaccount);
promise1.then(function(value) {
var accountnumber = value;
console.log(accountnumber);
web3.eth.personal.unlockAccount(accountnumber,pass, 1500);
auth.methods.approve().send({gas: '1000000',from: accountnumber});
console.log('Smart Contract approved ! ');
});
};
The account is getting created but while doing the transaction I am receiving the following error.
Approving the smart contract ..... Mining in process ! App.js:57
0x98f76b2673d545F55c0ff1e961f15EF0a7DfBaD3
App.js:71 Smart Contract
approved ! errors.js:29 Uncaught (in promise) Error: Returned error:
authentication needed: password or unlock
at Object.ErrorResponse (errors.js:29)
at index.js:125
at XMLHttpRequest.request.onreadystatechange (index.js:103)
at XMLHttpRequestEventTarget.dispatchEvent (xml-http-request-event-target.js:50)
at XMLHttpRequest._setReadyState (xml-http-request.js:288)
at XMLHttpRequest._onHttpResponseEnd (xml-http-request.js:459)
at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.
(xml-http-request.js:413)
at push../node_modules/stream-http/lib/response.js.exports.IncomingMessage.emit
(events.js:139)
at endReadableNT (_stream_readable.js:1030)
at afterTickTwo (index.js:31)
at Item.push../node_modules/process/browser.js.Item.run (browser.js:167)
at drainQueue (browser.js:131) ErrorResponse # errors.js:29 (anonymous) # index.js:125 request.onreadystatechange # index.js:103
XMLHttpRequestEventTarget.dispatchEvent #
xml-http-request-event-target.js:50 XMLHttpRequest._setReadyState #
xml-http-request.js:288 XMLHttpRequest._onHttpResponseEnd #
xml-http-request.js:459 (anonymous) # xml-http-request.js:413 emit #
events.js:139 endReadableNT # _stream_readable.js:1030 afterTickTwo #
index.js:31 push../node_modules/process/browser.js.Item.run #
browser.js:167 drainQueue # browser.js:131 setTimeout (async)
_fireError # index.js:72 sendTxCallback # index.js:465 (anonymous) # index.js:125 request.onreadystatechange # index.js:103
XMLHttpRequestEventTarget.dispatchEvent #
xml-http-request-event-target.js:50 XMLHttpRequest._setReadyState #
xml-http-request.js:288 XMLHttpRequest._onHttpResponseEnd #
xml-http-request.js:459 (anonymous) # xml-http-request.js:413 emit #
events.js:139 endReadableNT # _stream_readable.js:1030 afterTickTwo #
index.js:31 push../node_modules/process/browser.js.Item.run #
browser.js:167 drainQueue # browser.js:131 setTimeout (async)
runTimeout # browser.js:43
push../node_modules/process/browser.js.process.nextTick #
browser.js:156 nextTick # index.js:30 maybeReadMore #
_stream_readable.js:521 addChunk # _stream_readable.js:300 readableAddChunk # _stream_readable.js:278
push../node_modules/readable-stream/lib/_stream_readable.js.Readable.push
# _stream_readable.js:242 (anonymous) # response.js:47 write #
response.js:44
Edit: Changed the code to catch the errors
web3.eth.personal.unlockAccount(accountnumber,pass, 1500, function(err, result){
if(err){
alert("Error"+ err);
return;}
alert("Account Opening: "+ result);});
.....
auth.methods.approve().send({gas: '1000000',from: accountnumber}, function(err, result){
if(err){
alert("Error"+ err);
return;}
alert("Account address: "+ result);
console.log('Smart Contract approved ! ');});
The web3.eth.personal.unlockAccount is returning "true" but the still the auth.methods.approve is giving me the error.
So, after some major changes to the code, I am able to do the following from an onSubmit event on a react app.
Create an account.
Transfer some gas to it.
Unlock the account.
Sign a contract with the account.
Here is the code
onSubmit = async (event)=>{
event.preventDefault();
console.log('Approving the smart contract ..... Mining in process ! ');
var pass = "passsword1"
var newaccount = web3.eth.personal.newAccount(pass);
var promise1 = Promise.resolve(newaccount);
promise1.then(function(value) {
var accountnumber = value;
console.log(accountnumber);
web3.eth.personal.unlockAccount('0x197022acd263e8be0f6b65b10d1e5cdbaa244c17',"*****", 1500, function(err, result){
if(err){
alert("Error"+ err);
return;
}else {
alert("Parent Opening: "+ result);
web3.eth.sendTransaction({
from: "0x197022acd263e8be0f6b65b10d1e5cdbaa244c17",
to: accountnumber,
value: '100000000000000000',
}, function(err, transactionHash) {
if (err) {
console.log(err);
} else {
web3.eth.personal.unlockAccount(accountnumber,pass, 1500, function(err, result){
if(err){
alert("Error"+ err);
return;
}else{
console.log(web3.eth.getBalance(accountnumber));
alert("Child Opening: "+ result);
auth.methods.approve().send({gas: '20000000',from: accountnumber}, function(err, result){
if(err){
alert("Error"+ err);
return;
}else{
console.log("Account address: "+ result);
console.log('Smart Contract approved ! ');
}
});
}
});
}
});
}
});
};

Resources