React, TSX Parsing error: Expression expected - tsx

Below is REACT code for details page
Ticket is a primary object, and what i want to do is when downloading add the ticket name as .pdf filename.
So i need a solution to pass the concrete ticket name to the handleDownload function
In the render section there are no problem declaring ticket.ticketName etc. But with onClick the problem arises.
type TicketProps =
TicketStore.TicketState &
typeof TicketStore.actionCreators &
RouteComponentProps<{ticketId: string}>;
class Ticket extends React.PureComponent<TicketProps> {
public componentDidMount() {
this.ensureDataFetched();
}
private ensureDataFetched(){
this.props.requestTicket(+this.props.match.params.ticketId);
}
handleDownload = () =>{
Axios.get(`${apiUrl}/api/tickets/download/${this.props.match.params.ticketId}`,{responseType: 'arraybuffer',
headers: { "Content-Type": 'application/pdf' }
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', "test"+.pdf");
document.body.appendChild(link);
link.click();
});
}
public render() {
let ticket = this.props.ticket;
if(this.props.isLoading){
return <span>Laen andmeid...</span>;
}
if (ticket === undefined) {
return <h1>Piletit ei leitud</h1>;
}
let name = ticket.ticketName
return (
<React.Fragment>
<h3>Üritus: {ticket.ticketName}</h3>
<Table striped hover size="sm">
<tbody>
<tr>
<td className="details">Asukoht:</td>
<td>{ticket.eventLocation}</td>
</tr>
<tr>
<td className="details">Kuupäev:</td>
<td>{ticket.eventDate}</td>
</tr>
<tr>
<td className="details">Lisainfo:</td>
<td>{ticket.extraInfo}</td>
</tr>
<tr>
<td className="details">Pilet:</td>
<td>{ticket.pdfTicket}</td>
</tr>
</tbody>
</Table>
<Button onClick={this.handleDownload}>Lae alla</Button>
<Popup trigger={<button className="btn btn-primary">Show location on map</button>} position="bottom left">
<div><Maps aadress={ticket.eventLocation}></Maps>></div>
</Popup>
<Link to='../tickets'>
<Button color='primary' onClick={()=>{}}>
Tagasi
</Button>
</Link>
<br></br>
</React.Fragment>
);
}
}
export default connect(
(state: ApplicationState) => state.ticket,
TicketStore.actionCreators
)(Ticket as any);
I am getting parsing error after ticket?
Any thoughts?
Thanks

Use the following code without the question marks:
<Button onClick={()=>{this.handleDownload(ticket.id,ticket.ticketName)}}>Lae alla</Button>

The solution was to add
if(this.props.ticket===undefined){
return //something;
}
Before using the object.

Related

window.location.href in VUE 3 JS

I didn't get the issue here.
When I use
return window.location.href = 'https://www.google.com';
it works fine.
However, if I use my string variable. It doesn't work.Reloads back to page.
return window.location.href = this.navigationURL;
Full code:-
<table class="">
<tr
class="cursor-pointer"
v-for="currentView in authenticationMethodsAvailable"
:key="currentView.id"
>
<td class=""> (HERE)
**<button type= "button" #click="authenticationChoice(currentView['name'])" >**
<img
class="w-12 inline-block align-middle"
:src="showAuthenticationIcon(currentView['gitType'])"
/>
</button>
</td>
</tr>
</table>
The function being triggered
authenticationChoice(recieved) {
this.$store.state.gitSourceAuthenticationChoice = recieved;
this.$store.dispatch("gitSourceAuthenticationURL").then((response) => {
this.navigationURL = response["oauth2_redirect"];
console.log(this.navigationURL)
});
return this.navigationURL ;
// return window.location.href = String(this.navigationURL);
},
Remove the return which's breaking the code and move the code inside the then block as follows :
authenticationChoice(recieved) {
this.$store.state.gitSourceAuthenticationChoice = recieved;
this.$store.dispatch("gitSourceAuthenticationURL").then((response) => {
this.navigationURL = response["oauth2_redirect"];
console.log(this.navigationURL)
window.location.href = String(this.navigationURL);
});
},

How can I get a result from a POST request into a v-for?

I have something like this:
<table class="table">
<tbody>
<tr v-for="(option, index) in Weapons">
<td>Primary</td>
<td>[[ getWeaponType(option.WeaponType) ]]</td>
</tr>
</tbody>
</table>
In my Vue object, in methods, I have this:
getWeaponType: function(weaponTypeNumber){
axios.get('/path/to/api')
.then(response => {
return response.data
})
}
I send an ID and it returns the name for that ID. But I need for it to show in my table whose rows are being generated by the v-for. This isn't working since it is a Promise and the values are not showing. Is there any way I can achieve getting that value to show in the table? I didn't want to do it server side so I'm trying to see if I have any options before I do that.
May I suggest an alternative method?
data() {
return {
weaponsMappedWithWeaponTypes: [];
}
}
mounted() { // I am assuming the weapons array is populated when the component is mounted
Promise.all(this.weapons.map(weapon => {
return axios.get(`/path/to/api...${weapon.weaponType}`)
.then(response => {
return {
weapon,
weaponType: response.data
}
})
).then((values) => {
this.weaponsMappedWithWeaponTypes = values
})
}
computed: {
weaponsAndTheirWeaponTypes: function () {
return this.weaponsMappedWithWeaponTypes
}
}
And then in your template
<table class="table">
<tbody>
<tr v-for="(option, index) in weaponsAndTheirWeaponTypes">
<td>Primary</td>
<td>option.weaponType</td>
</tr>
</tbody>
</table>

Reloading Children Upon Database Change with React

I am still a major React beginner (self-learning) and can't seem to figure out how to reload a component's child elements when the database changes. Right now my set-up goes by the following image:
Component Layout Example.
I have three components contained in one larger component called Contact. The first component within Contact sits on top and is called SendAMessage, then there are two sitting underneath it called LeaveAComment and FetchComments (called CommentList in the image, but FetchComments in the actual code); LeaveAComment and FetchComments are both next to each other.
Right now FetchComments displays all comments contained in the database and LeaveAComment adds to the database. The problem is that the FetchComments component does not display any new comments that are created by the LeaveAComment component unless the tab is refreshed or navigated away from. I need help with trying to figure out a way to reload the displayed comment list contained in FetchComments with every database update. Or if there is a way to reload the FetchComments children from the 'Submit' button on LeaveAComment.
So far I understand that a parent component may pass props to a child component, but not necessarily the other way around; since LeaveAComment and FetchAComment are siblings, I am not sure what to do. Any help would be much appreciated. Here is the code I have so far:
export class LeaveAComment extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
comment: "",
date: ""
}
this.onChangeName = this.onChangeName.bind(this);
this.onChangeComment = this.onChangeComment.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChangeName(e) {
this.setState({
name: e.target.value
})
}
onChangeComment(e) {
this.setState({
comment: e.target.value
})
}
onSubmit(e) {
e.preventDefault();
console.log(`The values are ${this.state.name}, ${this.state.comment}, and ${this.state.date}`);
var data = new FormData(e.target);
//console.log(data)
fetch("api/Comment", {
method: 'POST',
body: data
})
// Clear input boxes
this.setState({
name: "",
comment: "",
date: ""
})
// Re-load FetchComments.js here?
}
render() {
return (
<div>
<header>
<h2> Leave A Comment </h2>
</header>
<form
onSubmit={this.onSubmit}
method="POST">
<label> Name: </label>
<input
name= "name"
className="form-control" value=''
value={this.state.name}
onChange={this.onChangeName}/>
<br />
<label> Comment: </label>
<input
name="comment"
className="form-control"
value={this.state.comment}
onChange={this.onChangeComment}/>
<br />
<div
name="date"
className="form-control"
value={new Date().getDate()}
hidden>
</div>
<input type="submit" value="Submit" className="btn btn-primary" />
</form>
</div>
);
}
}
export class FetchComments extends Component {
constructor() {
super();
this.state = {
loading: true,
commentList: []
};
}
componentDidMount() {
fetch('api/Comment')
.then(res => res.json())
.then(cl => this.setState({ loading: false, commentList: cl },
() => console.log("successfully fetched all comments", cl)))
}
renderCommentTable() {
return (
< div className = "container" >
<div className="panel panel-default p50 uth-panel">
<table className="table table-hover">
<thead>
<tr>
<th> Name </th>
<th> Comment </th>
<th> Time Stamp </th>
</tr>
</thead>
<tbody>
{this.state.commentList.map(c =>
<tr key={c.id}>
<td>{c.name} </td>
<td>{c.comment}</td>
<td> {new Intl.DateTimeFormat('en-US').format(c.comentDate)} </td>
</tr>
)}
</tbody>
</table>
</div>
</div >
)
}
render() {
let contents = this.state.loading ? <p> <img src="/Icons/LoadingPaopu.gif" alt="Loading Paopu Icon" /> </p>
: this.renderCommentTable(this.state.commentList);
return (
<div>
<h2> Comment List </h2>
{contents}
</div>
);
}
}

Calling a method into another method in vue

I'm trying to call a method from inside another method in vue.
What I get is an undefined in my console, but what I really want is the id that is called in the getId function
In a whole what I'm tring to do is use the addEvent function to get the checkbox events so that I can get a true or false from it and then send that to the saveCheckbox function and from the saveCheckbox function call the getId function to get the ID of that specific checkbox.
I hope I was able to explain it properly. If it's still unclear please let me know.
This is what I have
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categories" >
<td>
<input name="active" type="checkbox" v-model="category.active" #change="getId(category.id)" #click="addEvent">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: [
'attributes'
],
data(){
return {
categories: this.attributes,
}
},
methods: {
getId(id){
console.log(id);
return id
},
saveCheckbox(event){
console.log(this.getId());
},
addEvent ({ type, target }) {
const event = {
type,
isCheckbox: target.type === 'checkbox',
target: {
value: target.value,
checked: target.checked
}
}
this.saveCheckbox(event.target.checked)
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
You have to pass argument (Id) to getId method
Having a sort overview, you are not passing any Id to the method, and it trys to return that id. so maybe, that is what is not defined ?
The method calling is done well. with the this. keyword before it

Data inserting using jquery, AJAX in ASP.NET MVC4?

I am trying to insert data to the database. For that I am using ajax and jquery, but the values from textbox are coming null and inserting the same in database. Here is the code of html markup and jQuery button click event handling:
#using (#Html.BeginForm("VewResult", "States" ))
{
<table >
<tr>
<td>State ID</td> <td > #Html.TextAreaFor(m => m.StateID, new { ID = "txtStateid", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>District ID</td> <td> #Html.TextAreaFor(m => m.DistrictID, new { ID = "txtdistrictid", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>State Name</td> <td> #Html.TextAreaFor(m => m.StateName, new { ID = "txtStatendame", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td colspan="2"> <input type="Submit" id="btnAjax" name="btnAjax" value="Insert It"></td>
</tr>
</table>
<div id="result"></div>
}
#section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#btnAjax').click(function () {
alert($('#txtStateid').val());
var stateid = $('#txtStateid').val();
var districtid = $('#txtdistrictid').val();
var statename = $('#txtStatendame').val();
if (stateid != "" && districtid != "" & statename != "") {
$.ajax({
url: '/States/VewResult',
contentType: 'application/html; charset=utf-8',
data: { stid: stateid, districid: districtid, stname: statename },
type: 'POST',
dataType: 'html',
success(function (result) {
$('#result').html('Inserted Successfully');
})
});
error(function (xhr, status) {
alert(status);
})
}
else {
alert('Enter Stateid,districtid,statename');
}
});
});
</script>
}
Please try below code.
<table >
<tr>
<td>State ID</td> <td > #Html.TextAreaFor(m => m.StateID, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>District ID</td> <td> #Html.TextAreaFor(m => m.DistrictID, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>State Name</td> <td> #Html.TextAreaFor(m => m.StateName, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td colspan="2"> <input type="Submit" id="btnAjax" name="btnAjax" value="Insert It"></td>
</tr>
</table>
<div id="result"></div>
#section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#btnAjax').click(function () {
alert($('#txtStateid').val());
var stateid = $('#StateID').val();
var districtid = $('#DistrictID').val();
var statename = $('#StateName').val();
if (stateid != "" && districtid != "" & statename != "") {
$.ajax({
url: '/States/VewResult',
data: { stid: stateid, districid: districtid, stname: statename },
type: 'POST',
dataType: 'html',
success(function (result) {
$('#result').html('Inserted Successfully');
})
});
error(function (xhr, status) {
alert(status);
})
}
else {
alert('Enter Stateid,districtid,statename');
}
});
});
</script>
There is no need of form tag is required if you are calling as ajax. Or instead of jQuery ajax you can use Ajax.Beginform() . For this please refer
And your action will be
Public ActionResult VewResult(string stid,string districid,string stname)
{
//Your body
return;
}
Your are sending the data in HTML format to the Controller Action. Instead pass it as JSON. This link would be helpful to implement it.