Data of radio button not being saved in Postgres DB even after a success message - postgresql

Hi so I have these radio buttons where I want to save their data as json in my Postgres db . It is not being sent I get a message.success back that says I did but when i check my db nothing happens.
I don't exactly know where I am wrong so if u can help please do share.
PS: Im using Ant Design vue that's where the a- come from .
I do click on a button and it opens a modal where I have the radio buttons :
<template #modalite="{ record }">
<span>
<a-button
#click="showModalite(record)"
class="btn btn-sm btn-light mr-2"
>
<i class="fe fe-edit mr-2" />
Modalité
</a-button>
</span>
</template>
and here is my buttons code :
<a-modal
v-model:visible="visible"
:width="500"
#ok="ChangeModalite(modelInfo)"
>
<div class="row">
<a-radio-group name="radioGroup" v-model:value="traitement">
<div class="col-md-6">Négociation directe</div>
<div class="col-md-3">
<a-radio value="Négociation directe" v-model:checked="modalite.negociation" />
</div>
<div class="col-md-6">Appel à concurrence</div>
<div class="col-md-3">
<a-radio value="Appel à concurrence" v-model:checked="modalite.concurrence"/>
</div>
</a-radio-group>
</div>
</a-modal>
The script :
setup() {
const visible = ref(false)
const traitement = ref('Négociation directe');
const modalite = ref({
negociation:false,
concurrence:false,
})
const showModalite = (record) => {
modelInfo.value = record
modalite.value = { ...modalite.value, ...record.modalite }
visible.value = true
}
const ChangeModalite = (record) => {
console.log(record.id+": "+traitement.value)
axios.patch('/prop/' + record.id,{
modalite:modalite.value,
})
.then(()=>{
record.modalite=modalite.value
Object.assign(
dataSource.value.filter((item) => record.id === item.id),
record,
)
message.success(`successfully updated !!`)
visible.value = false
})
.catch((e)=>{
message.warning("smthg wrong ")
})
}
return {
dataSource,
modelInfo,
showModalite,
ChangeModalite,
modalite,
traitement,
}
},
}
So what happens now is i get the 'succefully updated ' msg without being really updated.where did i miss something?

I changed the type from json to string in my db everything works fine when I changed this line :axios.patch('/prop/' + record.id,{ modalite:modalite.value, }) to this axios.patch('/prop/' + record.id,{ modalite:traitement.value, })
so yeah data gets updated, still don't know why with the json type it's not working but at least i found a way if u have an explanation or suggestion it will be appriciated .

Related

Next JS 13 data send from client component to server side component but show Not found

JS 13 and inside my ReadMoreButton client component i push my article data using useRouter hook of NEXT.
Not i can not use useRouter hook inside NEXT.JS server component so here i fetch searchParams and fetch that data.
here problem is before rendering i am checking if searchParams are defined or not not if i check in development everything work fine it render data but in production mode it show page not found error even if data is correctly send.
when i run next build it give me following output Output
and i am running side in production mode using next start and it show page not found when i do /article?serchParamsData.
You can check my whole code here : https://github.com/ssiwach8888/Next.JS-News-App
i also deploy production build on Vercel but it also show same error.
I am using NEXT.JS 13 with typescript
# ReadMoreButton.tsx "First Control goes here."
"use client";
type Props = {
article: NewsData;
};
import { useRouter } from "next/navigation";
//For navigate to SSC
const ReadMoreButton = ({ article }: Props) => {
const router = useRouter();
const handleClick = () => {
const queryString = Object.entries(article)
.map(([key, value]) => `${key}=${value}`)
.join("&");
const url = `/article?${queryString}`;
router.push(url);
};
return (
<button
className="bg-orange-400 h-10 rounded-b-lg dark:text-gray-900 hover:bg-orange-500"
onClick={handleClick}
>
Read More
</button>
);
};
export default ReadMoreButton;
# Article.tsx "Then we navigate to this page."
type Props = {
searchParams?: NewsData;
};
import { notFound } from "next/navigation";
import LiveTimestamp from "../Components/LiveTimestamp";
import Link from "next/link";
const ArticlePage = ({ searchParams }: Props) => {
if (
(searchParams && Object.entries(searchParams).length === 0) ||
!searchParams
) {
return notFound();
}
const article: NewsData = searchParams;
return (
<article className="mt-6">
<section className="flex flex-col lg:flex-row pb-24 px-0 lg:px-10">
<img
src={article.image === "null" ? "/no-image.jpeg" : article.image}
alt={article.title}
className="h-50 max-w-md mx-auto md:max-w-lg lg:max-w-xl object-contain rounded-lg shadow-md"
/>
<div className="px-8">
<Link legacyBehavior href={article.url || ""}>
<a target="_blank">
<h1 className="headerTitle hover:underline cursor-pointer px-0 pb-2">
{article.title}
</h1>
</a>
</Link>
<div className="flex divide-x-2 space-x-4">
<h2 className="font-bold">
By: {article.author !== "null" ? article.author : "Unknown"}
</h2>
<h2 className="font-bold pl-4">Source: {article.source}</h2>
<p className="pl-4">
<LiveTimestamp
time={
article.published_at === "null" ? "" : article.published_at
}
/>
</p>
</div>
<p className="pt-4 text-lg">{article.description}</p>
</div>
</section>
</article>
);
};
export default ArticlePage;
You just need to put the article page in [bracket] to make it dynamic so next js can fetch all pages otherwise it would display blank----
change article folder to [article]
more reference https://nextjs.org/docs/routing/dynamic-routes

REACT Multiple Registration

I have a problem with React, so I created script and it doesn't work.
This should:
Render first state step (it's working) (Component First)
Here is error, it don't see default values.(name & email
After click Save And Continue it should save files to data.
And going to next steps in cases.
The error is
bundle.js:34147 Uncaught ReferenceError: email is not defined
function send(e){
e.preventDefault()
}
function nextStep(){
this.setState({
step:this.state.step + 1
})
}
function nextStep(){
this.setState({
step:this.state.step - 1
})
}
function saveAndContinue(e) {
e.preventDefault()
// Get values via this.refs
var data = {
name : this.refs.name.getDOMNode().value,
email : this.refs.email.getDOMNode().value,
}
this.props.saveValues(data)
this.props.nextStep()
};
var fieldValues = [
name : null,
email : null,
];
function saveValues(fields) {
return (
fieldValues = Object.assign({}, fieldValues, fields)
);
}
class Registration extends React.Component{
constructor () {
super()
this.state = {
step:1
}
}
render() {
switch (this.state.step) {
case 1:
return <First fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues} />
case 2:
return <Two fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues}/>
case 3:
return <Third fieldValues={fieldValues}
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues}/>
case 4:
return <Success fieldValues={fieldValues} />
}
}
}
class First extends React.Component{
render(){
return(
<form onSubmit ={send}>
<div className="group">
<input className="text" type="text" ref="name" defaultValue={this.props.fieldValues.name}/>
<span className="highlight"></span>
<span className="bar"></span>
<label>Write Name</label>
</div>
<div className="group">
<input className="text" type="email" ref="email" defaultValue={this.props.fieldValues.email} />
<span className="highlight"></span>
<span className="bar"></span>
<label>Write Your Mail</label>
</div>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</form>
)
}
}
There is no Two, Third and Success classes in your code, so I'm assuming they are similar to the First class.
A global function doesn't need this keyword. But in this case, you have to put saveAndContinue inside First class if it need to access the state.
In React, normally you don't have to set default value for input.
Link the input value to the state, and then setState in onChange event.
The string in placeholder is shown when the state is empty.
The code below shows how to work with input tag in React:
<input
value={this.state.inputValue}
onChange={e => {
this.setState({ inputValue: e.target.value });
}}
type="text"
placeholder="default value"
/>
Note that the state will updates onChange rather than click the save button.
Does this solve your problem?

How to search collection in meteor with more parameters

I need help with searching the meteor collection with more parameters.
I am using search query and filters to see certain objects from a collection. The problem is that I want client to load whole collection and then reactively change what the user sees, but only changing the subscribe, not calling server again. Thill now search query + one filter is working okay, but only if I call server every time something changes. Now in my code below you can see that I am doing it with if else elements, but that is not a good way. Any suggestion will help. Thank you.
Template.jobs.onCreated( function showOnCreate() {
Meteor.subscribe('Jobs');
this.searchQuery = new ReactiveVar('');
this.remoteQuery = new ReactiveVar(false);
this.typeQuery = new ReactiveVar(false);
});
Template.jobs.helpers({
job: () => {
query = Template.instance().searchQuery.get();
remoteQuery = Template.instance().remoteQuery.get();
typeQuery = Template.instance().typeQuery.get();
let regex = new RegExp( query, 'i' );
// **************************
// the problem starts here
// **************************
if (Router.current().params.slug) {
const companyJobs = Company.findOne({slug: Router.current().params.slug}).jobs;
if ( companyJobs !== undefined) {
return Meteor.subscribe('Jobs', {'_id': { '$in': companyJobs }});
}
return false
} else if (Router.current().params.slug === undefined && remoteQuery === true ) {
return Job.find({ $or: [ { Name: regex }, { Description: regex }, ] , Remote: true, positionType: [],});
} else if (typeQuery = '') {
return Job.find({ $or: [ { Name: regex }, { Description: regex }, ] , positionType: typeQuery, });
},
// -------*****************************
employer: () => {
if (Router.current().params.slug === undefined) {
Meteor.subscribe('Companies');
return 'Poslodavac: ' + Company.findOne({_id: Template.currentData().CompanyId}).Name;
}
return false
},
jobUrl: () => {
Meteor.subscribe('Companies');
companySlug = Company.findOne({_id: Template.currentData().CompanyId}).slug;
return ('/company/' + companySlug + '/job/' );
}
});
Template.jobs.events({
'click .positionType': (event, templateInstance) => {
if (Template.instance().remoteQuery.get().lenght > 1){
Template.instance().typeQuery.set(Template.instance().remoteQuery.get().push(event.target.value));
console.log(Template.instance().remoteQuery.get())
} else {
console.log(Template.instance().remoteQuery.get())
console.log('ggggggg')
Template.instance().typeQuery.set(event.target.value);
}
},
'click #remoteFriendly': (event, templateInstance) => {
Template.instance().remoteQuery.set(!Template.instance().remoteQuery.get());
},
});
Html tempalte with filters:
<template name="jobs" >
<div>
<p>Filteri:</p>
<span>
<input type="checkbox" id="remoteFriendly" name="remote"> <span for="remoteFriendly"> Remote friendly? </span>
</span>
<span>
<p>Tip pozicije:</p>
<input type="checkbox" class="positionType" id="1" value="Programiranje" > <span for="1"> Programiranje </span>
<input type="checkbox" class="positionType" id="2" value="Dizajn" > <span for="2"> Dizajn </span>
<input type="checkbox" class="positionType" id="3" value="Marketing" > <span for="3"> Marketing </span>
<input type="checkbox" class="positionType" id="4" value="Ostalo" > <span for="4"> Ostalo </span>
</span>
</div>
{{#each job}}
<div style="border: 0.1rem solid black; margin: 1cm; padding: 5px; max-width: 420px;" > <!-- OVO JE PRIVREMENI STIL, OBRISATI-->
<p> Posao: {{Name}} <br> Opis: {{Description}}</p>
<p> {{employer}} </p>
<p>Remote friendly?: {{Remote}}</p>
<p>Tip pozicije: {{positionType}}</p>
<p> Saznajte vise OVDE</p>
</div>
{{/each}}
<p id="nesto"></p>
</template>
Welcome to SO!
You seem to be confused between Pub/Sub and Collection.find.
You should first realize that the 2 are different mechanisms, which provide different functionalities.
Pub/Sub indeed sends data from your Server into your Client's Minimongo database. But this data is not displayed yet.
Collection.find is used on your Server against your actual MongoDB, and on your Client against your local Minimongo DB.
Therefore on your client, once you have correctly subscribed to your server publication (typically at app level or template level / in onCreated hook), you can directly call Jobs.find in your helpers (or anywhere else) to get your documents, without having to change the subscription (unless the latter needs new parameters).
There should be nothing wrong with your commented code:
return Job.find({'_id': { '$in': companyJobs }});
In general, avoid any expensive computation in helpers (like Meteor.subscribe), as helpers may be executed many times without you noticing it. Your Meteor.subscribe('Companies') should also go to template level (i.e. in onCreated hook).
Therefore, instead of doing your if / else conditions in your helper, simply do it once at your template level. To account for your need to use a value from another document in another collection, why not just passing directly the company's slug as an argument to your Jobs subscription, and performing the computation Server-side? Or even just subscribing to everything, as your current initial subscription seems to do.
Then your helper will just use Jobs.find, which queries against your Client's local minimongo DB, leaving your Server unbothered.

Im getting some weird errors with MaterialUI Stepper "Cannot read property stepIndex of undefined"

I'm using MaterialUI and I'm getting the error -
"Uncaught TypeError: Cannot read property 'stepIndex' of undefined"
In my Chrome console
I haven't had this error with any of the other Material-UI React Components. I am pretty new to React so if this is a stupid mistake please bear with me.
I cant seem to solve the problem.
I'm using React 5.3.1.
My code:
class HorizontalLinearStepper extends React.Component {
handleNext() {
const {stepIndex} = this.state;
this.setState({stepIndex: stepIndex + 1,finished: stepIndex >= 2});
};
handlePrev() {
const {stepIndex} = this.state;
if (stepIndex > 0) {
this.setState({
stepIndex: stepIndex - 1
});
}
};
getStepContent(stepIndex) {
switch (stepIndex) {
case 0:
return 'Select campaign settings...';
case 1:
return 'What is an ad group anyways?';
default:
return 'You\'re a long way from home sonny jim!';
}
}
render() {
const {finished, stepIndex} = this.state;
return (
<div>
<Stepper activeStep={stepIndex}>
<Step>
<StepLabel>Select campaign settings</StepLabel>
</Step>
<Step>
<StepLabel>Create an ad group</StepLabel>
</Step>
</Stepper>
<div style={contentStyle}>
{finished ? (
<p>
<a
href="#"
onClick={(event) => {
event.preventDefault();
this.setState({stepIndex: 0, finished: false});
}}
>
Click here
</a> to reset the example.
</p>
) : (
<div>
<p>{this.getStepContent(stepIndex)}</p>
<div style={{marginTop: 12}}>
<FlatButton
label="Back"
disabled={stepIndex === 0}
onTouchTap={this.handlePrev}
style={{marginRight: 12}}
/>
<RaisedButton
label={stepIndex === 2 ? 'Finish' : 'Next'}
primary={true}
onTouchTap={this.handleNext}
/>
</div>
</div>
)}
</div>
</div>
);
}
}
export default HorizontalLinearStepper;
Thanks!
<FlatButton
label="Back"
disabled={stepIndex === 0}
onTouchTap={this.handlePrev.bind(this)}
style={{marginRight: 12}}
/>
<RaisedButton
label={stepIndex === 2 ? 'Finish' : 'Next'}
primary={true}
onTouchTap={this.handleNext.bind(this)}
/>
You need to bind the handlers as they will be run in a different context and will loose the right meaning of this, so we bind the handlers to keep the right context of this.

Mongodb return an Empty array

I am trying to make a range query and show the data in my ejs view
EJS View "historicos.ejs"
<h1>historicos</h1>
<form action="/historicos/buscar">
<input type="text" name='inicio' id='inicio'></li>
<input type="text" name='final' id='final'></li>
<br>
<button type="submit">Buscar</button>
</form>
<% if(typeof his !== 'undefined'){
his.forEach(function(dati){%>
<%= dati.temp %>
<%= dati.hum %>
<%= dati.date %>
<br/>
<%});
}; %>
I am using a controller with 2 methods, 1 for render the page and one to manage the query.
Controller "grafi.js"
var Si = require('../models/sis');
exports.getPagehis = function(req, res) {
if (req.user) return res.redirect('/');
res.render('historicos');
};
exports.getHis= function(req, res, next) {
ini = req.body.inicio;
fin = req.body.final;
console.log(ini)
console.log(fin)
Si.find({"date": {"$gte":ini, "$lt":fin}},function(err, his) {
console.log(his);
if(err) return next(err);
res.render('historicos', {
his:his
});
});
};
and this is my router file
router.get('/historicos', hiController.getPagehis);
router.get('/historicos/buscar', hiController.getHis);
if I write manually ini and fin to make the query(using this format YYYY-MM-DDThh:mm), I mean without the req.body.inicial and req.body.final, it work well but when I request the information from the view I got this fields undifined.
what can i do to solve this?
the problem was form and the request in general adding method="get" in the form and update the controller with:
var Url = require('url');
...
queryparams = Url.parse(req.url,true).query;
ini = queryparams.ini;
fi = queryparams.fi;
... make the query to mongo db
with this code is possible to get the values in the input files passed in the url