I am developing a script in react and nodejs. The idea is about displaying the content from json to the react page using sweet alert 2.
The output does not shows results which is suppose to display the content from the json file.
Here are my codes
import React from 'react';
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';
const MySwal = withReactContent(Swal);
const json = require('json-loader!./myfilepath.json');
class pageJSONOCR extends React.Component
{
getData = () =>
{
console.log("Button Clicked");
MySwal.fire({
title: 'Success!',
text: "Button is clicked",
type: 'success',
showCancelButton: false,
confirmButtonText: 'View File'
}).then((result) => {
if (result.value) {
MySwal.fire(
'The Content Of Json File',
`${json}`
)
}
})
}
render()
{
console.log("Header - Rendered");
return(
<div className="container">
<div className="py-5 text-center">
<div className="jumbotron">
<div className="container">
<h1>Out Put</h1>
<hr/>
<p className="lead">Check The JSON File</p>
<button className="btn btn-primary" value="Submit" onClick={this.getData}>Submit</button>
</div>
</div>
</div>
</div>
);
}
}
export default pageJSONOCR;
If there is any solutions do help me.
Thanks in advance!
use sweetalert2-react-content
import withReactContent from 'sweetalert2-react-content';
import Swal from 'sweetalert2';
const basic = withReactContent(Swal.mixin({
title: 'Success',
text: 'text here.',
confirmButtonText: "Okay.",
showCloseButton: true,
showCancelButton: true,
cancelButtonText: 'Cancel'
}));
...
<div>
{
basic.mixin({
title: <i>title</i>
}).fire()
}
</div>
Related
I'm building my first Vue app, most of it works fine, but when I click in a post to open the selected post, it doesn't show properly ( Image, title and content don't show ) in the post page, it show the card with the buttons but not the other content, everything shows in home page.
I hope some kind soul can show me some light...
P.S. I'm a beginner so simple terms would be appreciated.
This is my Home page.
<template>
<v-container>
<v-alert border="left" close-text="Close Alert" color="green accent-4" dark dismissible v-if="this.$route.params.message">
{{ this.$route.params.message }}
</v-alert>
<v-row no-gutters>
<v-col sm="4" class="pa-3" v-for="post in posts" :key="post._id">
<v-card class="pa-1" :to="{ name: 'post', params: { id: post._id } }">
<v-img height="250" :src="`/${post.image}`"></v-img>
<v-btn class="ml-4 mt-3" small outlined color="indigo">
{{ post.category }}
</v-btn>
<v-card-title class="headline">
{{ post.title }}
</v-card-title>
<v-card-text class="py-0">
{{ post.content.substring(0, 100) + '...' }}
</v-card-text>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
import API from '../api'
export default {
name: 'Home',
data() {
return {
posts: [],
};
},
async created() {
this.posts = await API.getAllPost();
}
};
</script>
and this is my post page
<template>
<v-container>
<v-row no-gutters>
<v-col sm="10" class="pa-4 mx-auto">
<v-card class="pa-2">
<v-img :src="`${ post.image }`"></v-img>
<v-card-actions class="pb-0">
<v-row class="mt-1 mx-1">
<v-col sm="2">
<v-btn small outlined color="primary">{{ post.category }}</v-btn>
</v-col>
<v-col sm="10" class="d-flex justify-end">
<v-btn color="success" text :to="{ name: 'edit-post', params: { id: post._id } }">Edit</v-btn>
<v-btn color="red" text #click="deletePost(post._id)">Delete</v-btn>
</v-col>
</v-row>
</v-card-actions>
<v-card-subtitle class="headline">
<h3>{{ post.title }}</h3>
</v-card-subtitle>
<v-card-text class="grey--text">
<p>{{ post.content }}</p>
<p>{{ post.created }}</p>
</v-card-text>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
import API from '../api';
export default {
data() {
return {
post: {},
};
},
async created(){
const response = await API.getPostByID(this.$route.params.id);
this.post = response;
},
methods: {
async deletePost(id) {
const response = await API.deletePost(id);
this.$router.push({ name: 'Home', params: { message: response.message } });
},
},
}
</script>
I am new to learning React. I have build a small application which includes React,Node and MongoDB. I have two modules here, the Create data and the Edit data. My question is regarding the Select component from Reacts's built in library. When I create a user, I enter his availability time slots(isMulti in Select) from a component. On Submit, this data along with the the slots is getting inserted in the Mongo Db.This is all fine. I am having problem when loading the page for edit. How to make the previously selected items from dropdown show up on page load. The other fields show up fine with componentDidMount().
Here is what my update module looks like-
// eslint-disable-next-line
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Select from 'react-select';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
// Connecting from front end to backend with Axios
import axios from "axios";
export default class EditPanel extends Component {
constructor(props) {
super(props);
//defining this
this.onChangefield1 = this.onChangefield1.bind(this);
this.onChangefield2 = this.onChangefield2.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.handleChange=this.handleChange.bind(this);
this.state = {
field1: "",
field2: "",
timeSlots:[],
filterOptions:[
{ label:"9:00am to 10:00am", value: "9:00am to 10:00am" },
{ label: "10:00am to 11:00am", value: "10:00am to 11:00am" },
{ label: "11:00am to 12:00pm", value: "11:00am to 12:00pm" },
{ label: "12:00pm to 01:00pm", value: "12:00pm to 01:00pm" },
{ label: "01:00pm to 02:00pm", value: "01:00pm to 02:00pm" },
],
selectedOption:[]
}
}
componentDidMount() {
console.log("inside componentmount");
axios.get('http://localhost:5000/someEndpoint/' + this.props.match.params.id)
.then(response => {
this.setState({
field1: response.data.field1,
field2: response.data.field2,
mailId: response.data.mailId,
timeSlots:response.data.timeSlots,
selectedOption: response.data.timeSlots,
})
console.log("Meow"+response.data.timeSlots);
})
.catch(function (error) {
console.log(error);
})
}
onChangefield1(e) {
this.setState({ field1: e.target.value });
}
onChangefield2(e) {
this.setState({ field2: e.target.value });
}
// This is for insertion of any new selected list items
handleChange = selectedOption => {
console.log(selectedOption.value);
this.setState({ selectedOption: selectedOption.value }); // selected option value
console.log(selectedOption);
var dataArray = [];
for(var o in selectedOption) {
dataArray.push(selectedOption[o].value);
this.setState({ timeSlots: dataArray });
console.log(this.timeSlots);
}
};
onSubmit(e) {
e.preventDefault();
const panel =
{
field1: this.state.field1,
field2: this.state.field2,
timeSlots:this.state.timeSlots
}
axios.post('http://localhost:5000/someEndpoint/update/' + this.props.match.params.id, panel)
.then(res => console.log(res.data));
console.log("calling from edit");
window.location = '/';
}
render() {
return (
<div>
<h3>Edit Panel Info</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Field 1: </label>
<input type="text"
required
className="form-control"
value={this.state.field1}
onChange={this.onChangefield1}
/>
</div>
<div className="form-group">
<label>field2: </label>
<input
type="text"
className="form-control"
value={this.state.field1}
onChange={this.onChangefield2}
/>
</div>
<div className="form-group">
<label>Time Slots</label>
<div>
<Select
options={this.state.filterOptions} // Options to display in the dropdown
isMulti
value={this.state.selectedOption} // would like to see the values we have in DB
onChange={this.handleChange}
closeIcon="close"
/>
</div>
</div>
<div className="form-group">
<input type="submit" value="Edit Panel" className="btn btn-primary" />
</div>
</form>
</div>
)
enter code here
}
}`enter image description here`
[enter image description here][1]
[1]: https://i.stack.imgur.com/NliEH.png
The mongo db data looks like
timeSlots
:
Array
0
:
"10:00am to 11:00am"
1
:
"12:00pm to 01:00pm"
I'm trying to achieve inserting the option value tags using MERN, but whenever I tried to insert in the database it inserts nothing, I can't seem to find the issue. I just started learning MERN. Anyways this is the code I wrote. Any help will deeply be appreciated. Thanks in Advance :)
export default class AddClient extends Component {
constructor(props) {
super(props);
this.onChangeExisting = this.onChangeExisting.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
existing: "",
};
}
onChangeExisting(e) {
this.setState({
existing: e.target.value,
});
}
onSubmit(e) {
e.preventDefault();
const client = {
existing: this.state.existing,
};
console.log(client);
axios
.post("http://localhost:5000/clients/create", client)
.then((res) => console.log(res.data));
}
render() {
return (
<>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Existing Customer: </label>
<select
ref="userInput"
required
className="form-control"
value={this.state.existing}
onChange={this.onChangeExisting}
>
<option key="Male" value="Male">
Male
</option>
<option key="Female" value="Female">
Female
</option>
</select>
</div>
<button type="submit" onClick={this.onSubmit}>submit </button>
</form>
</>
);
}
}
You dont Have <button> Tag in side a <form> tag .
so when & how submit event can call?
pls Add
<button type="submit" onClick={this.onSubmit}>submit </button>
inside form tag.
Already solved it just has to change put data instead of e
onChangeExisting(e) {
this.setState({
existing: e.target.value,
});
}
to
onChangeExisting(data) {
this.setState({
existing: data.value,
});
}
and putting a variable like this:
const existing= [
{ key: "Not Started", label: "Not Started", value: "Not Started" },
{ key: "In Progress", label: "In Progress", value: "In Progress" },
{ key: "Completed", label: "Completed", value: "Completed" },
];
and calling it via:
npm i react-select
then import Select from "react-select"; on the page you want to use it
<Select options={existing} onChange={this.onChangeExisting} />
I'm creating a Blog using Angular 7, MongoDB and NodeJS. So far I have created a component that loops through all the posts from the database and displays them on a single page.
<div class="container-fluid">
<div class="row" *ngIf="posts.length > 0" >
<div class="col-lg-12 col-md-12 col-xl-12 text-center" *ngFor="let post of posts ">
<div class="post-preview" >
<h2 class="post-title text-center">
{{ post.title }}
</h2>
<h3 class="post-subtitle text-center">
{{ post.subtitle }}
</h3>
<br>
<div class="post-image">
<img [src]="post.imagePath" [alt]="post.title">
</div>
<br>
<p class="post-meta text-center">{{post.date}}</p>
</div>
</div>
</div>
</div>
This is for displaying all the blog posts on a single page. When a user clicks on a single post he should be directed to a page that shows detailed information for that post only (like the blog content). How do I implement that?
In the posts.service I have the following function for getting a single post.
getPost(id: string) {
return this.http.get<{_id: string, title: string, subtitle: string, content: string, date: Date, imagePath: string}>(
'http://localhost:3000/api/posts/' + id);
}
And on the backend I have the following route:
router.get("/:id", (req, res, next) => {
Post.findById(req.params.id).then(post => {
if (post) {
res.status(200).json(post);
} else {
res.status(404).json({
message: 'Post not found!'
});
}
});
});
I found the answer here: https://codecraft.tv/courses/angular/routing/parameterised-routes/
The soloution:
[1]
Spefify the parameterised route in router as:
{ path: 'blog/:postId', component: SinglePostComponent }
[2]
Create a link to direct the user to the the specified blog post
<a [routerLink]="['/blog', post.id]" > </a>
[3]
In the SinglePostComponent.ts put the following code:
export class SinglePostComponent implements OnInit {
post: Post;
private postId: string;
constructor(
private route: ActivatedRoute,
private postsService: PostsService
) {}
ngOnInit() {
this.route.paramMap.subscribe((paramMap: ParamMap) => {
this.postId = paramMap.get('postId');
this.postsService.getPost(this.postId).subscribe(postData => {
this.post = {id: postData._id, title: postData.title, subtitle: postData.subtitle,
content: postData.content, date: postData.date, imagePath: postData.imagePath};
});
}
);
}
}
I have a form that is being used to edit and update the record of a specific Id and I'm able to access the Id within my GET method for my route with req.params.annotationId, but when I try to use the POST version of getting a parameter with req.body.annotationId I get a value returned of NULL. I also tried to use req.params.annotationId and it returned the :annotationId placeholder for the route. Is this because the field is not present in the form? which would make sense because body-parser looks for values present in the fields?
This is the resulting query from the POST method:
Executing (default): SELECT `annotation_id` AS `annotationId`, `annotation_date` AS `annotationDate`,`user_id` AS `userId`, `createdAt`, `updatedAt`, `userUserId` FROM `annotation` AS `annotation` WHERE `annotation`.`user_id` = 1 AND `annotation`.`annotation_id` = NULL LIMIT 1;
Here is my route:
appRoutes.route('/edit/:annotationId')
.get(function(req, res){
console.log('This is the url path ' + req.originalUrl);
console.log(req.params.annotationId);
models.Annotation.find({
where: {
userId: req.user.user_id,
annotationId: req.params.annotationId
},attributes: ['annotationId', 'annotationDate']
}).then(function(annotation){
res.render('pages/annotation-edit.hbs',{
annotation: annotation,
user: req.user,
editMode: req.originalUrl
});
})
})
.post(function(req, res){
console.log("POST method triggered");
console.log(req.params.annotationId);
models.Annotation.find({
where: {
userId: req.user.user_id,
annotationId: req.body.annotationId
}
}).then(function(annotation){
if (annotation) {
console.log("Annotation exists");
annotation.update({
annotationDate: req.body.annotationDate,
userId: req.user.user_id
}).success(function() {
console.log("Annotation Updated");
});
}
})
});
Here is my annotation model:
module.exports = function(sequelize, DataTypes) {
var Annotation = sequelize.define('annotation', {
annotationId: {
type: DataTypes.INTEGER,
field: 'annotation_id',
autoIncrement: true,
primaryKey: true
},
annotationDate: {
type: DataTypes.DATE,
field: 'annotation_date'
},
userId: {
type: DataTypes.STRING,
field: 'user_id'
}
},
{
freezeTableName: true,
},
classMethods: {
associate: function(db) {
Annotation.belongsTo(db.User)
}
}
});
return Annotation;
}
Here is the form for the POST request:
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="annotation-form">
<form action="/app/edit/:annotationId" method="post">
<div class="annotation-form-header">
<img class="user-image" src="http://placehold.it/80x80" alt="Generic placeholder image">
<label for="annotation-date">Annotation Date:</label>
<input type="date" name="annotationDate" id="annotation-form-date" value="{{annotation.annotationDate}}">
</div>
<button type="submit" id="create-annotation-button">Update Annotation</button>
</form>
req.body.annotationId with get annotationID from data in form like :
<form action="/app/edit" method="post">
<input name="annotationId" type="hidden" value="121313">
<div class="annotation-form-header">
<img class="user-image" src="http://placehold.it/80x80" alt="Generic placeholder image">
<label for="annotation-date">Annotation Date:</label>
<input type="date" name="annotationDate" id="annotation-form-date" value="{{annotation.annotationDate}}">
</div>
<button type="submit" id="create-annotation-button">Update Annotation</button>
</form>
```
req.params.annotationId get annotationID from URL : /edit/4465465
<form action="/app/edit/:annotationId" method="post"> <- invalid URL
The form should use the handlebars object to pass in the current Id selected like so,
<form action="/app/edit/{{annotation.annotationId}}" method="post">
<input name="annotationId" type="hidden" value="121313">
<div class="annotation-form-header">
<img class="user-image" src="http://placehold.it/80x80" alt="Generic placeholder image">
<label for="annotation-date">Annotation Date:</label>
<input type="date" name="annotationDate" id="annotation-form-date" value="{{annotation.annotationDate}}">
</div>
<button type="submit" id="create-annotation-button">Update Annotation</button>
</form>
The route should then be change from .find to .update:
.post(function(req, res){
console.log("POST method triggered");
console.log(req.params.annotationId);
models.Annotation.update({
annotationId: req.body.annotationId,
annotationDate: req.body.annotationDate,
},{where:{
userId: req.user.user_id,
annotationId: req.body.annotationId
}}).then(function(){
console.log("Annotation was Updated");
res.redirect('/app');
});
});