API Calls based on Condition - reactjs

I have a dropdown with 2 values (value 1 and value 2) and i have 2 API POST calls . i have one button. what i want is is the value one is selected perform the POST call for value 1 if value 2 is selected perform API post for value 2 and show their respective results. please guide me how to achieve this
MY POST Call:
submit(){
const article = { model: this.state.model,
dataset:this.state.course,
path:this.state.checkbox };
axios.post('http://localhost:3000/home', article)
.then(response => this.setState({ s3path: response.data.s3_path , triton_output: response.data.triton_output, confidence: response.data.confidence,
inference_model:response.data.inference_model, loading: false,
}))
.catch(error => {
this.setState({ errorMessage: error.message });
console.error('There was an error!', error);
});
this.openModal();
this.state.loading=true
}
submit1(){
const article = { model: this.state.model,
dataset:this.state.course,
path:this.state.checkbox };
axios.post('http://localhost:3000/home', article)
.then(response => this.setState({ x: response.data.x , y: response.data.y_output, height: response.data.height,
inference_model:response.data.inference_model, loading: false,
}))
.catch(error => {
this.setState({ errorMessage: error.message });
console.error('There was an error!', error);
});
this.openModal();
this.state.loading=true
}
In this Post call the "Model:this.state.model" is the selected dropdown value. i need to call the api based on selected dropdown value

I hope this code will solve your issue;
var Test = React.createClass({
onClick: function(event){
if("Dropdown value check")
{
func1();
}
else{
func2();
}
},
render: function(){
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
});

Related

How to change "Request to join" button text to "Join Meeting" in iframe

I'm new to daily-co integration in react js. Can you please suggest how to change
"Request to Join" text to "Join Meeting". Thank in advance.
At present in Iframe all content is coming. Can any one please suggest how to change
the "Request to Join" text to "Join Meeting".
My Observations:
One api is calling at the time of page is loaded:
https://b.daily.co/call-ui/16c545a8520b661e39dc13c62b335ffea4cb3651/locales/en/translation.js
{ ....
"haircheck": {
....
"setup": {
"requestToJoin": "Request to join",
"title": "Are you ready to join?",
}
},
}
//React Class component:
import React from 'react';
import DailyIframe from '#daily-co/daily-js';
import Cookies from 'universal-cookie';
import axios from '../../util/axios';
import util from '../../util/util';
const cookies = new Cookies();
class VideoCallFrame2 extends React.Component {
constructor(props) {
super(props);
this.iframeRef = React.createRef();
this.state = {
authorizationToken: 'Bearer ------------',
roomName: '',
room: null,
token: null,
rooms: [],
roomUrlWithToken: null,
isVideoHidden: false,
joinedObject: null,
status: '',
askedQuestions: [],
};
}
componentDidMount() {
this.daily = DailyIframe.wrap(
this.iframeRef.current,
{
showLeaveButton: true,
});
this.setState({
...this.state,
roomUrlWithToken: this.props.meetingRoomUrl
});
this.startRoom();
let temp = this.daily.meetingState();
this.setState({ status: temp });
this.get_candidate_position();
}
get_candidate_position = (e) => {
this.setState({
positionDetails: response.data.candidate[0]
})
}
onHandleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
joinMeetingEvents = () => {
// Meeting related events
this.daily.on('loading', () => { console.log('Loading......') })
this.daily.on('loaded', () => { console.log('Loaded......') })
this.daily.on('joining-meeting', () => { console.log('Joining......') })
this.daily.on('joined-meeting', () => {
console.log('Joined......')
})
this.daily.on('app-message', (e) => {
console.log('app-messageapp-message app-message>>>>>>> ', e)
})
this.daily.on('left-meeting', (e) => {
console.log('Left Meeting......', e)
this.props.history.push('/thankyou')
})
this.daily.on('participant-joined', (e) => {
console.log('Partcipand Joined......', e);
this.setState({
...this.state,
isVideoHidden: true
})
if (this.state.joinedObject.user_id == '') {
}
})
this.daily.on('error', (e) => {
console.log('ERROR......', e)
})
}
leftMeeeting = () => {
this.daily.leave();
this.daily.destroy();
}
startRoom = async () => {
let res = await this.daily.join({
url: this.props.meetingRoomUrl
})
this.setState({
...this.state,
joinedObject: null
})
this.daily.on('loading', () => { console.log('Loading......') })
this.daily.on('loaded', () => { console.log('Loaded......') })
this.daily.on('joining-meeting', () => { console.log('joining-meeting......') })
this.daily.on('joined-meeting', () => {
console.log('Joined meeting......');
})
this.daily.on('joined-meeting', () => {
console.log('Joined meeting......');
})
this.daily.on('meeting-session-updated', () => {
console.log('meeting-session-updated......');
});
this.daily.on('access-state-updated', (evt) => {
console.log('access-state-updated......', evt);
if (evt.access.level == 'lobby') {
//Some code
}
});
this.daily.on('participant-joining', () => { console.log('participant-joining') })
this.daily.on('left-meeting', (e) => {
this.props.history.push('/thankyouPage');
});
this.daily.on("app-message", (e) => {
let Arr = this.state.askedQuestions;
if (
e &&
e.data &&
e.data.message &&
e.data.message.endInterview == "end") {
this.leftMeeeting();
}
});
this.daily.on('participant-joined', (e) => {
console.log('Partcipand Joined......', e);
setTimeout(() => {
this.daily.sendAppMessage({ message: { intervieweraskedQuestions: this.state.askedQuestions } }, '*');
}, 3000)
})
this.daily.on('error', (e) => {
console.log('ERROR......', e)
})
}
render() {
return (
<div className="" style={{ height: '450px' }}>
<iframe className="Video-Frame video-call-frame"
title="video call iframe"
ref={this.iframeRef}
allow="camera; microphone; fullscreen; display-capture"
></iframe>
</div>
)
}
}
export default VideoCallFrame2;
I work at Daily. :) "Request to join" is shown for private rooms with "knocking" enabled. We use this language because clicking the button will alert the room owner to let you in, so you do need to ask to join -- you can't just go straight in.
This can be turned off though. If you make the room public, it will say "Join meeting" instead of "Request to join" because anyone can join. Alternatively, you can make a meeting token for anyone trying to enter a private room so they don't need to ask to join. (In this case, the button text would also be updated to "Join meeting").
More generally, you can't update button text to something custom in the Daily Prebuilt UI, but you can build your on custom UI with our APIs. That's probably too much effort just to update one button, though. :)
I have not used daily.co before but I did a little digging and confirmed my suspicions: As far as I can tell, this is not possible.
In order to for a page to edit the contents of an iFrame, the frame must be on the same origin as its parent page, as per the Same Origin Policy.
Your page is on the origin http://localhost:3001, while the frame is on an origin owned by Daily, e.g. https://server.daily.co.
This policy exists for security reasons, an example is imagine some website https://attacker.com with a frame to https://bankaccount.com, without this policy the attacker could change a button on the frame from "Click to send all money to attacker" to "Click to receive your $1 million reward!"
The only method I have found that may be plausible after doing a couple searches for "origin", "host", etc. on docs.daily.co is this reference page for "Daily's Video Component System (VCS)", but from what I can tell this cannot solve the problem as this only allows you to add an overlay to the video call, not the frame itself.

scrollIntoView does not work on first load and after each refresh

I am seeing a very strange behavior in my chat. Once the chat is opened, the scroll moves only a tiny bit down only when there are images in the chat. When there is only text, it goes all the way down. Also, if I close the chat and open it again, the scroll goes all the way down regardless of the content. However, If I refresh the page, the scroll returns to its weird behavior. I am puzzled as to why this is happening. Here's my code:
Here's how the chat starts:
startChat () {
document.getElementById("myForm").style.display = "block";
const ref = firebase.firestore().collection('Chats').doc(this.state.uid).collection('Messages');
const query = ref.orderBy('timestamp', 'desc').limit(10)
this.unsubFromMessages = query.onSnapshot((snapshot) => {
if (snapshot.empty) {
console.log('No matching documents.');
firebase.firestore().collection('Chats').doc(this.state.uid).
set({
name: this.state.displayName,
uid: this.state.uid,
email: this.state.email
}).then(console.log("info saved"))
.catch((error) => {
console.log("Error saving info to document: ", error);
});
}
snapshot.docChanges().reverse().forEach((change) => {
if (change.type === 'removed') {
console.log(change.doc.data().content)
}
else if (change.type === 'added') {
this.setState(state => {
const messages = [...state.messages, {id: change.doc.id, body: change.doc.data()}]
return {
messages
}
})
setTimeout( this.scrollToBottom(), 2000)
}
else if (change.type === 'modified') {
const filteredMessages = this.state.messages.filter(message => message.body.allowed === "yes")
this.setState(state => {
const messages = [...filteredMessages, {id: change.doc.id, body: change.doc.data()}]
return {
messages
}
})
setTimeout( this.scrollToBottom(), 2000)
}
});
}, (error) => {console.log(error)});
}
Here's the scroll function:
scrollToBottom = () => {
this.myRef.current.scrollIntoView({ behavior: "smooth" });
}
Here's the JSX of the chat:
<div className="form-popup" id="myForm">
<form className="form-container" onSubmit={this.chatFormSubmit}>
<h1>Chat</h1>
<label htmlFor="msg"><b>Message</b></label>
<div className="chatArea" id='messages'>
{
this.state.messages.map((message, index) => {
return message.body.uid === this.state.uid && !message.body.imageUrl
?
<p className="message-sent" key={index}>{message.body.content}</p>
:
message.body.uid === this.state.uid && message.body.imageUrl
?
<img src={message.body.imageUrl} className="message-sent" key={index}></img>
:
<p className="message-received" key={index}>{message.body.content}</p>
})
}
<div style={{ float:"left", clear: "both" }}
ref={this.myRef}>
</div>
</div>
And if the functions for closing and submitting messages to the chat are of any use, here they are:
closeForm() {
document.getElementById("myForm").style.display = "none";
this.setState({messages: []})
this.unsubFromMessages();
}
chatFormSubmit(e) {
e.preventDefault();
this.setState({ writeError: null });
firebase.firestore()
.collection('Chats')
.doc(this.state.uid)
.collection('Messages')
.doc()
.set({
docId: this.state.docId,
content: this.chatArea.current.value,
allowed: "yes",
timestamp: new Date(),
uid: this.state.uid,
name: this.state.displayName,
email: this.state.email
}, { merge: true })
.catch((error) => {
this.setState({ writeError: error.message });
})
.then(this.chatArea.current.value = '')
}
Again, I figured it out myself. Instead of calling "this.scrollToBottom()" in setTimeout, I should have simply passed it like this setTimeout( this.scrollToBottom, 2000). That is why setTimeout was not working and the scroll stopped half way. Credit goes to Felix Kling's comment in ReactJS: setTimeout() not working?.

componentDidMount function in React

I am designing a quiz in React, and I am having one final problem with my code.
There are 7 questions in the MongoDB Database which I am pulling data from. The idea is, every time the "Next" button on my quiz is clicked, the next question should load after the user has answered the previous question. Currently, only the first question loads, and I am having trouble loading up the remaining questions. I have a componentDidMount function which I guess would be responsible for loading information from the MongoDB database.
componentDidMount() {
axios.get('/challenge', {
params: {
questionID: "Phish01",
//"Phish0" + this.state.currentQuestion;
},
})
For every question in the database, I have added a field named "questionID" which identifies the question. Since there are 7 questions, each question has an ID of Phish01, Phish02....Phish07.
Obviously looking at the code, only the first question loads up, which is fine. However, I am unsure as to the best method in loading up the remaining questions. I was thinking of using some form of concatenation as seen in the commented out piece of code above, but don't think that's the correct way of going about it.
I also was considering making a new function as seen below, but similar to before, I think I am doing it wrong.
/*setNextQuestion() {
axios.get('/challenge', {
params: {
questionID: "Phish0" + this.state.currentQuestion;
},
})
//questionID: "Phish0" + 1;
if (this.state.currentQuestion !== prevState.currentQuestion) {
this.setState(() => {
return{
disabled: true,
questionID: questionID,
}
});
}}*/
I thought I would also add this code sample in too:
constructor(props) {
super(props);
this.state = {
currentQuestion: 0,
userInput: null, // user has not answered a question yet at the start
points: 0,
options: [],
disabled: true, // Next button is disabled by default
optionEnabled: true, //options should be enabled by default
};
If anyone is able to help or point me towards a resource that would help me in understanding my issue, that would be great!
Thanks!
Added in the rest of the code file:
Class Challenge extends Component {
constructor(props) {
super(props);
this.state = {
currentQuestion: 0,
userInput: null, // user has not answered a question yet at the start
points: 0,
// options : ["Hello"],
options: [],
isLoaded: false,
quizzes: {},
disabled: true, // Next button is disabled by default
optionEnabled: true, //options should be enabled by default
intervalIsSet: false,
gameOver: false,
};
}
// this function below should be responsible for loading the data from the MongoDB database
componentDidMount() {
axios.get('/challenge', {
params: {
questionID: "Phish01",
//"Phish0" + this.state.currentQuestion;
},
})
.then((response) => {
const result = response.data;
console.log(response.data);
this.setState({
isLoaded: true,
quizzes: result,
options: result.options,
answer: result.answer,
answerDetails: result.answerDetails,
wrongAnswer: result.wrongAnswer,
});
}).catch((error) => {
this.setState({
isLoaded: true,
error,
});
});
}
nextQuestion = () => {
const { chosenAnswer, answer, points } = this.state;
alert(this.state.wrongAnswer);
alert(this.state.answerDetails);
if (chosenAnswer === answer) {
this.setState({
points: this.state.points + 1
});
}
this.setState({
currentQuestion: this.state.currentQuestion + 1
});
console.log(this.state.currentQuestion);
};
//this function should be responsible for loading the remaining questions
/*setNextQuestion() {
axios.get('/challenge', {
params: {
questionID: "Phish0" + this.state.currentQuestion;
},
})
//questionID: "Phish0" + 1;
if (this.state.currentQuestion !== prevState.currentQuestion) {
this.setState(() => {
return{
disabled: true,
questionID: questionID,
}
});
}
}*/
lastQuestion = () => {
if (this.state.currentQuestion === 7) { //array starts at 0
this.setState({
gameOver: true
});
}
};
//when user clicks on an option, the "Next" button should then be enabled
checkAnswer(chosenAnswer) {
if (chosenAnswer == this.state.answer) {
alert('You have chosen the correct answer!');
alert('Click Next to continue');
this.setState({
disabled: false,
optionEnabled: false,
});
//alert(this.state.answerDetails);
} else {
alert('You have selected the wrong answer');
alert('Click Next to continue');
this.setState({
disabled: false,
optionEnabled: false,
});
}
}
render() {
const {options, userInput, currentQuestion, gameOver} = this.state;
if (gameOver) {
return (
<div className="result">
<h3>The quiz is over. Final score is {this.state.points} points</h3>
</div>
);
} else {
return (
<div className="quizChallenge">
<h2>{this.state.quizzes.description} </h2>
<table id="t01">
<tbody>
<tr>
{this.state.options.map((option) => {
return (
<td key={option}>
<button
disabled={!this.state.optionEnabled}
onClick={() => this.checkAnswer(this.state.options.indexOf(option))}>
{option}
</button></td>
);
})}
</tr>
</tbody>
</table>
{currentQuestion < 8 &&
<button
className="ui inverted button"
disabled={this.state.disabled}
onClick={this.nextQuestion}
>Next
</button>
}
{currentQuestion === 7 &&
<button
className="ui inverted button"
disabled={this.state.disabled}
onClick={this.lastQuestion}
>Finish Challenge!
</button>
}
</div>
);
}
}
}
export default Challenge;

How to prevent from form submission when email exists error and how to set value in form itself without getting reset

The below code shows the form submit function. the form gets submitted but when email exist error occurs the form gets reset. how to prevent form getting reset?.
submit = values => {
// print the form values to the console
let formValues = {
clu_first_name: values.clu_first_name,
clu_last_name: values.clu_last_name,
clu_email: values.clu_email,
clu_sec_email: " ",
// "clu_state":0,
// "clu_city":0,
// "clu_zip":0,
// "clu_address":null,
clu_contact: values.clu_contact,
lgn_password: values.clu_pass,
cli_id: client_id, // SRM id
cat_id: values.cat_id,
dep_id: values.dep_id,
usr_id: usr_ID,
clu_id: values.clu_id
};
console.log("formValues-fmp", formValues);
let decodeFormValues = { json: JSON.stringify(formValues) };
this.setState({ formSubmitting: true });
fetch(
`${Utils.getApiBaseUrl()}/fmp/client/addClientUser`,
Utils.getPostOptions(decodeFormValues)
)
.then(response => {
return response.json();
})
.then(res => {
if (res.status == 1) {
toast.success(" Successfully created.", {
position: toast.POSITION.TOP_RIGHT,
autoClose: 3000
});
this.fetchUserList(client_id);
this.setState({ formSuccess: true, formError: false, opened: false });
} else {
toast.error("Email exists", {
position: toast.POSITION.TOP_RIGHT,
autoClose: 3000
});
this.setState({
formError: true,
formSuccess: false,
errorText: res.data
});
}
this.setState({ formSubmitting: false });
});
};
Below is my form code, here because of onsubmitsuccess it get reset, I want to get reset after success if any error occurs the form must have the values.
const afterSubmit = (result, dispatch) => dispatch(reset("createuser"));
CreateUserForm = reduxForm({
form: "createuser",
multipartForm: true,
onSubmitSuccess: afterSubmit
})(CreateUserForm);

ReactJS: reloading/re-rendering a component on click

I have a component called "categories", where I have 2 buttons active and inactive. Each button calls an api to either activates or deactivates the selected record. However, the button part and the api part are running completely fine and getting proper response after getting the task done. But, I need the "categories" component to reload/re-render after the api response has returned the success code.
I googled for the solution but the answers I got were little confusing for me because I am currently learning the ReactJS.
Here is my code:
...
setInactive(e)
{
Axios
.get("/api/category/deactivate/" + $(e.currentTarget).data('token'))
.then((response) => {
if (response.data.success == true)
{
this.setState({
state: this.state
});
}
});
}
setActive(e)
{
Axios
.get("/api/category/reactivate/" + $(e.currentTarget).data('token'))
.then(response => {
if (response.data.success == true)
{
this.setState({
state: this.state
});
}
});
}
render()
{
...
(category.status == "Y")
? <button data-token={category.token} className="lightRed" onClick={this.setInactive}>Inactive</button>
: <button data-token={category.token} className="green" onClick={this.setActive}>Active</button>
...
}
Also can this code be reduced/optimized..?
I figured out the solution (I got an idea from another answer, but unfortunately I lost that link. I'll paste it if I find it again).
Here is my solution:
...
componentWillMount()
{
this.fetchData();
}
fetchData()
{
Axios
.get("/api/categories")
.then(response => this.setPagination(response.data));
}
setStatus(token, status)
{
Axios
.get("/api/category/status/" + token + "/" + status)
.then((response) => {
if (response.data.success == true)
{
this.setState({
message: <Alerts alertClass="alert-success">
Category status has been modified successfully.
</Alerts>
});
this.fetchData();
}
else
{
this.setState({
message: <Alerts alertClass="alert-danger">
{response.data.message}
</Alerts>
});
}
});
}
setPagination(response)
{
this.setState({
categories: response.data,
totalItemsCount: response.total,
itemsCountPerPage: response.per_page,
activePage: response.current_page,
paginationIndex: ((response.current_page - 1) > 0)
? (((response.current_page - 1) * response.per_page) + 1)
: 1
});
}
pagination(pageNumber)
{
Axios
.get("/api/categories?page=" + pageNumber)
.then(response => this.setPagination(response.data));
this.setState({
activePage: pageNumber
});
}
render()
{
return (
...
{
(category.status == "Y")
? <button className="buttons tiny lightRed" onClick={() =>
this.setStatus(category.token, 'N')
}>Inactive</button>
: <button className="buttons tiny green" onClick={() =>
this.setStatus(category.token, 'Y')
}>Active</button>
}
...
)
}
I hope this may come in handy for someone. However, if there is any room for improvement then please let me know. :)

Resources