Vuejs/Posgres - When clicked on button I want to save a value in db postgresql - postgresql

Hi so I have a view where I have a button , When it's clicked I want a value to be saved in the db . What I get now is nothing like I click on button but nothing happens .
Here's the code I have :
<a-button type="primary" class="mb-4 text-center mr-1 float-right" #click="onSubmit">Confirm</a-button>
in my script I have:
setup(){
const onSubmit = () => {
axios.post("/insertstatut/"+876,"added").then((res)=>{
message.success(`statut ajouté`)
router.push({
path:'/cand',
}).catch(error => {
console.log('error', error);
})
} ,
)
}
}
Please if u have any idea what I should do , do share thank you.

you are using composition api feature setup in your vue code,
you need to return the methods or properties u wish to use in in your template.
setup () {
return {
onSubmit: () => {}, //some method u want to use later in template ,
show: false, // or some property
}
}

this is how your component should look
<template>
<a-button
type="primary"
class="mb-4
text-center
mr-1float-right"
#click="onSubmit"
>
Confirm
</a-button>
</template>
<script>
import AButton from './button-path/AButton.vue'
import axios from 'axios'
export default {
componets: { AButton },
setup() {
const onSubmit = () => {
axios.post('/insertstatut/' + 876, 'added').then((res) => {
message.success(`statut ajouté`)
router
.push({
path: '/cand',
})
.catch((error) => {
console.log('error', error)
})
})
}
// Expose your constants/methods/functions
return {
onSubmit,
}
},
}
</script>

Related

Ionic React: InAppPurchase2 states "Product does not exist"

I was following the example shown at:
Ionic React: Implementing InAppPurchase 2 on React Hooks
I kept getting errors saying that:
"
InAppPurchase[objc]: Product (signatureyearly) does not exist or is not sucessfully initialized.
"
I have tried "com.myappname.app.signatureyearly" as well but I get similar errors.
I have double confirmed that my app bundle id is "com.myappname.app" and my IAP product ID is "signatureyearly" it is a renewal subscription and it is "Ready to submit".
Really need help with this, has been trying to figure this out for many days.
This is what I have written so far.
Thank you so much !!!!
import React, { useState, useEffect } from 'react';
import { InAppPurchase2 as iap, IAPProduct } from "#ionic-native/in-app-purchase-2";
export const TestStore: React.FC = () => {
//declare variables
const [productPrice, setPrice] = useState('')
const [product, setProduct] = useState([]) as any
//initiate initInAppPurchase function
useEffect(() => {
const init = async () => {
await initInAppPurchase();
}
init();
}, []);
const initInAppPurchase = () => {
iap.verbosity = iap.DEBUG;
iap.register({
id: "signatureyearly",
type: iap.PAID_SUBSCRIPTION
});
iap.ready(() => {
let product = iap.get('signatureyearly');
setPrice(product.price)
setProduct(product)
})
iap.refresh();
}
//if user clicks purchase button
const purchaseProduct = () => {
if (product.owned) {
alert('Product already owned, click restore button instead!')
} else {
iap.order('signatureyearly').then(() => {
iap.when("signatureyearly").approved((p: IAPProduct) => {
//store product
p.verify();
p.finish();
});
})
iap.refresh();
}
}
//if user clicks retore or promo code button
const restore = () => {
iap.when("signatureyearly").owned((p: IAPProduct) => {
if (product.owned) {
//store product
} else {
alert("You have not purchased this product before.")
}
});
iap.refresh();
}
return (
<div>
<button onClick={purchaseProduct}>TEST 4 :Buy for {productPrice}</button>
<button onClick={restore}>Restore</button>
<button onClick={restore}>Promo code</button>
</div>
);
};

testing input events with react testing library

I've created a small keypad app in react and I'm trying to test the input event on the app and for some reason I am not getting the expected result. I'm trying to test it to failure and success. The test I'm running is this below, I want to input 1995 (the correct combination), click the unlock button and ultimately have a message return Unlocked! but it only returns Incorrect Code! which should only happen if the code is incorrect or the input field is empty. But it shouldn't be empty as I have filled it out in the test..
here is a codesandbox: https://codesandbox.io/s/quirky-cloud-gywu6?file=/src/App.test.js:0-26
Any ideas?
test:
const setup = () => {
const utils = render(<App />);
const input = utils.getByLabelText("input-code");
return {
input,
...utils
};
};
test("It should return a successful try", async () => {
const { input, getByTestId } = setup();
await act(async () => {
fireEvent.change(input, { target: { value: "1995" } });
});
expect(input.value).toBe("1995");
await act(async () => {
fireEvent.click(getByTestId("unlockbutton"));
});
expect(getByTestId("status")).toHaveTextContent("Unlocked!");
});
the component I'm trying to test
import React, { useState, useEffect } from "react";
import Keypad from "./components/Keypad";
import "./App.css";
import "./css/Result.css";
function App() {
//correctCombination: 1995
const [result, setResult] = useState("");
const [locked, setLocked] = useState("Locked");
const [tries, setTries] = useState(0);
const [hide, setHide] = useState(true);
//Along with the maxLength property on the input,
// this is also needed for the keypad
useEffect(() => {
(function() {
if (result >= 4) {
setResult(result.slice(0, 4));
}
})();
}, [result]);
const onClick = button => {
switch (button) {
case "unlock":
checkCode();
break;
case "clear":
clear();
break;
case "backspace":
backspace();
break;
default:
setResult(result + button);
break;
}
};
const checkCode = () => {
if (result === "1995") {
setLocked("Unlocked!");
setTries(0);
} else if (tries === 3) {
setHide(false);
setLocked("Too many incorrect attempts!");
setTimeout(() => {
setHide(true);
}, 3000);
} else {
setLocked("Incorrect code!");
setTries(tries + 1);
}
};
const clear = () => {
setResult("");
};
const backspace = () => {
setResult(result.slice(0, -1));
};
const handleChange = event => {
setResult(event.target.value);
};
return (
<div className="App">
<div className="pin-body">
<h1>Pin Pad</h1>
<div className="status">
<h2 data-testid="status">{locked}</h2>
</div>
<div className="result">
<input
maxLength={4}
type="phone"
aria-label="input-code"
data-testid="inputcode"
placeholder="Enter code"
onChange={handleChange}
value={result}
/>
</div>
{hide ? <Keypad onClick={onClick} /> : false}
</div>
</div>
);
}
export default App;

Using react-select Async with loadOptions and redux-form

I'm using react-select library to display a select box. I'm using Select.Async because I need to pull my options from an API. I use Select with loadOptions and it works during the intial page render. However, I'm also using redux-form which can change the value of a Field dynamically (using change). However, when I change the value of the Field like this, the value of the input does change (and I can verify this), but react-select's loadOptions is never called again (even though I thought it was supposed to be listening to a change of value). My question is, is there a way to dynamicaly call loadOptions every time the input value changes?
Thanks,
Edit: Answered on github here
this.state = {
store: '',
};
this.handleStoreSelect = this.handleStoreSelect.bind(this);
handleStoreSelect = (item) => {
this.setState({
store: item.value
}
};
<Select.Async
name="storeID"
value={this.state.store}
loadOptions={getStores}
onChange={this.handleStoreSelect}
/>
const getStores = () => {
return fetch(
"api to be hit",
{
method: 'get',
headers: {
'Content-Type': 'application/json'
}
}
)
.then(response => {
if(response.status >= 400){
throw new Error("error");
}
return response.json()
})
.then(stores => {
let ret = [];
for(let store of stores) {
ret.push({value: store._id, label: store.name})
}
return {options: ret};
})
.catch(err => {
console.log('could not fetch data');
console.log(err);
return {options: []}
})
};
Using this we can fetch the data and pass this object in the loadoptions.
copy this code outside the class. and also i'm posting the code to be implemented for loadoptions
It might be a better solution than this, but a quick one is to set a ref to your Select.Async component, and when a change action is triggered (like the change of an input - your case, or one button click event - like in the code below) you can update its options. I'm using a similar example with the example of their docs.
class YourClass extends React.Component {
getOptions = (input, callback) => {
setTimeout(function () {
callback(null, {
options: [
{value: 'one', label: 'One'},
{value: 'two', label: 'Two'}
]
});
}, 500);
};
updateOptions = () => {
this.selectAsync.state.options.push(
{value: 'three', label: 'Three'}
)
}
render() {
let props = this.props;
return (
<div>
<Select.Async
ref={selectAsync => this.selectAsync = selectAsync}
loadOptions={this.getOptions}
/>
<button onClick={this.updateOptions}>
Load more items
</button>
</div>
)
}
}

How can I use props to auto-populate editable redux-form fields in React?

I'm new to React so I've tried to show as much code as possible here to hopefully figure this out! Basically I just want to fill form fields with properties from an object that I fetched from another API. The object is stored in the autoFill reducer. For example, I would like to fill an input with autoFill.volumeInfo.title, where the user can change the value before submitting if they want.
I used mapDispatchtoProps from the autoFill action creator, but this.props.autoFill is still appearing as undefined in the FillForm component. I'm also confused about how to then use props again to submit the form. Thanks!
My reducer:
import { AUTO_FILL } from '../actions/index';
export default function(state = null, action) {
switch(action.type) {
case AUTO_FILL:
return action.payload;
}
return state;
}
Action creator:
export const AUTO_FILL = 'AUTO_FILL';
export function autoFill(data) {
return {
type: AUTO_FILL,
payload: data
}
}
Calling the autoFill action creator:
class SelectBook extends Component {
render() {
return (
....
<button
className="btn btn-primary"
onClick={() => this.props.autoFill(this.props.result)}>
Next
</button>
);
}
}
....
function mapDispatchToProps(dispatch) {
return bindActionCreators({ autoFill }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SelectBook);
And here is the actual Form where the issues lie:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import { createBook } from '../actions/index;
class FillForm extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
onSubmit(props) {
this.props.createBook(props)
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
const { fields: { title }, handleSubmit } = this.props;
return (
<form {...initialValues} onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<input type="text" className="form-control" name="title" {...title} />
<button type="submit">Submit</button>
</form>
)
}
export default reduxForm({
form: 'AutoForm',
fields: ['title']
},
state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
}), {createBook})(FillForm)
I think you're mixing up connect and reduxForm decorators in the actual form component. Currently your code looks like this (annotations added by me):
export default reduxForm({
// redux form options
form: 'AutoForm',
fields: ['title']
},
// is this supposed to be mapStateToProps?
state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
}),
/// and is this mapDispatchToProps?
{createBook})(FillForm)
If this is the case, then the fix should be as simple as using the connect decorator as it should be (I also recommend separating this connect props to their own variables to minimize confusions like this):
const mapStateToProps = state => ({
initialValues: {
title: state.autoFill.volumeInfo.title
}
})
const mapDispatchToProps = { createBook }
export default connect(mapStateToProps, mapDispatchToProps)(
reduxForm({ form: 'AutoForm', fields: ['title'] })(FillForm)
)
Hope this helps!

Can the Polymer paper-dropdown-menu be bound using ngControl?

I am trying to create a form in Angular2 using the Polymer paper-dropdown-menu control. Is there a way to bind the selected value of the dropdown to the control in my component? I have tried everything with no luck. Has anyone gotten over this hurdle?
An example of a working paper-input is:
template:
<paper-input type="password"
ngControl="password"
ngDefaultControl>
</paper-input>
component:
constructor(private fb:FormBuilder) {
this.loginForm = fb.group({
password: new Control("")
});
}
Is there something similar for paper-dropdown-menu? Either binding to the value or the text itself would be fine. Thanks!
You need a custom ControlValueAccessor. I didn't succeed using a ControlValueAccessor for the paper-dropdown-menu itself but for the paper-menu or paper-listbox inside the paper-dropdown-menu like
const PAPER_MENU_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => PaperMenuControlValueAccessor), multi: true});
#Directive({
selector: 'paper-listbox',
host: {'(iron-activate)': 'onChange($event.detail.selected)'},
providers: [PAPER_MENU_VALUE_ACCESSOR]
})
export class PaperMenuControlValueAccessor implements ControlValueAccessor {
onChange = (_:any) => {
};
onTouched = () => {
};
constructor(private _renderer:Renderer, private _elementRef:ElementRef) {
console.log('PaperMenuControlValueAccessor');
}
writeValue(value:any):void {
//console.log('writeValue', value);
this._renderer.setElementProperty(this._elementRef.nativeElement, 'selected', value);
}
registerOnChange(fn:(_:any) => {}):void {
this.onChange = fn;
}
registerOnTouched(fn:() => {}):void {
this.onTouched = fn;
}
}
See also
ngModel Binding on Polymer dropdown (Angular2)
Bind angular 2 model to polymer dropdown