Variable isn't getting updated [duplicate] - html

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 24 days ago.
I have this script. In the createApp function, I have a variant variable.
And you can see that I do a console.log(variant) below axios.get(). It logs 'ealjapd (it is the variant content).
But it is supposed to change to results.data.variants[0]. But it isn't changing... any suggestions?
<script>
if (document.querySelector('#add-to-cart-form')) {
const app = Vue.createApp({
delimiters: ['${', '}'],
setup() {
let variant = Vue.ref('ea´ljapd');
axios.get('/products/{{product.handle}}.js').then((results) => {
variant = Vue.ref(results.data.variants[0]);
console.log(variant);
});
const addToCart = (event) => {
event.preventDefault();
axios
.post('/cart/add.js', data)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
return {
variant,
};
},
}).mount('#add-to-cart-form');
}
</script>
I can't figure it out, I need help

try this
variant.value = results.data.variants[0]
reference here
https://vuejs.org/guide/essentials/reactivity-fundamentals.html#reactive-variables-with-ref

Related

NextJS router.query not giving the ID param [duplicate]

This question already has answers here:
useRouter/withRouter receive undefined on query in first render
(9 answers)
Closed 3 months ago.
I am making crud using nextjs as frontend and CodeIgniter as backend I am following a tutorial where the frontend is reactjs. in reactJs when the updating part of the crud comes we can use the react-router-dom useParam function to get the ID but in nextJS we use router.query and it does not work so I am now stuck on how to get the id of the specific column to update it
const { id } = router.query;
const getProductById = async () => {
// if (id !== undefined && id != null && id > 0) {
const response = await axios.get(`http://localhost:8080/companies/${id}`);
setName(response.data.name);
setCreatedBy(response.data.createdBy);
console.log(id);
// }};
This is the code I am using and it gives an error that
`http://localhost:8080/companies/undefined`
You can get query.id on the server-side and then pass it to the client-side
export async function getServerSideProps(context) {
const { id } = context.query;
console.log(`query id: ${id}`);
return { props: { id } };
}
Now id is passed as prop to the client:
const YourComponent=(props)=>{
console.log("passed id prop",props.id)
}
Router query can be empty on the first render, on statically optimized pages.
try wrapping the code in useEffect
useEffect(()=>{
const { id } = router.query;
const updateProduct = async (e) => {
e.preventDefault();
await axios.patch(`http://localhost:8080/companies/${id}`, {
company_name: name,
created_by: createdBy,
});
router.push("/products");
};
},[router.query])

Is there any way to pass selector parameter inside puppeteer page.$$eval and then bind to the map? [duplicate]

This question already has answers here:
How can I pass variable into an evaluate function?
(7 answers)
Closed 1 year ago.
I tried different ways like add it to unnamed function, but without success. Thank you.
var selector = '.tile-hover-target';
const prods = await page.$$eval(resultsSelector, function (msgs) {
return msgs.map(function (selector, msg) {
return {
link: msg.querySelector(selector).href.trim(),
}
}.bind(null, selector))
});
According to the Puppeteer documentation, arguments need to be passed after the function. This works fine:
var sel = '.product-card__main';
const prods = await page.$$eval(resultsSelector, function (msgs, sel) {
return msgs.map(function (selector, msg) {
return {
link: msg.querySelector(selector).href.trim(),
}
}.bind(null, sel))
}, sel);

how to mock on global object in backstop.js/puppetter

So backstop.js provides ability to run custom script against underlying engine. I use puppeteer as an engine so I try to mock Date.now with 'onReadyScript':
page.evaluate('window.Date.now = () => 0; Date.now = () => 0;');
...
page.addScriptTag({
// btw `console.log` here is not executed, do I use it in wrong way?
content: 'Date.now = () => 0;'
});
...
page.evaluate(() => {
window.Date.now = () => 0;
Date.now = () => 0;
});
Last one, I think, is modifying Date in context of Node, not inside the puppeteer, but anyway tried that as well.
Nothing worked, script under the test still output real Date.now. Also I checked Override the browser date with puppeteer but it did not help me.
Yes, I know I'm able to skip particular selectors, but it does not always make sense(think about clock with arrows).
After trying onBeforeScript with evaluateOnNewDocument() it works for me. Complete script:
module.exports = async function (page, scenario) {
if (!page.dateIsMocked) {
page.dateIsMocked = true
await page.evaluateOnNewDocument(() => {
const referenceTime = '2010-05-05 10:10:10.000';
const oldDate = Date;
Date = function(...args) {
if (args.length) {
return new oldDate(...args);
} else {
return new oldDate(referenceTime);
}
}
Date.now = function() {
return new oldDate(referenceTime).valueOf();
}
Date.prototype = oldDate.prototype;
})
}
};
Reason: onReadyScript is executed when page under testing has already been loaded and executed. So code is bound to original Date by closure, not the mocked version.

can't access value from inside then to outside then Promise

I'm trying to get value from inside to outside then using promise.
In my controller I have:
async Sample(userId: number)
{
let data = this.userService.getAffectedExpertisesPromise(userId);
await data.then((uri) =>
{
uri.forEach((exp: Expertise) =>
{
this.empList.push(exp.name);
});
})
return this.empList;
}
On ngOnInit, I call this function:
this.Sample(25).then(item =>
{
item.forEach((expLibelle: String) =>
{
listExp.push(expLibelle);
});
console.log("------------------------ List Size Inside: " + listExp.length);
});
console.log("------------------------ List Size Outside : " + listExp.length);
In service user file, I have:
getAffectedExpertisesPromise(id: number): Promise<any>
{
return this.http.get(`${this.baseUrl}/users/expertisesObj/${id}`).toPromise();
}
It produces:
------------------------ List Size Outside : 0
------------------------ List Size Inside: 3
As you saw:
the size inside then is 3 --> Correct answer
the size inside then is 0 --> Wrong answer
Could you please help me solving that issue ?.
Big thanks.
Why not trying using XMLHttpRequest.
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:6227/api/auth/users', false);
request.send(null);
HTH.

How to pass value from promise to parent scope? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've been trying to get user locales using expo, on react-native. Problem is, i need to get the promise value and pass it to return function. The value is currently 'undefined'.
This is the code:
export default locales = () => {
var locals;
Expo.DangerZone.Localization.getCurrentLocaleAsync().then((value) => {
locals = value;
});
return locals;
}
How do i get the promise value and return it on function?
return locals; happens before your promise returns and so will be undefined. You need to use a callback:
export default locales = (callback) => {
Expo.DangerZone.Localization.getCurrentLocaleAsync().then((value) => {
return callback(value);
});
}
then you can access the value like this:
your_module.locales((locals)=>{
// use locals here
});
or, if you have access to async/await in newer versions of node:
export default locales = async () => {
let value = await Expo.DangerZone.Localization.getCurrentLocaleAsync()
return value;
}
and then you would call the function like this:
let locals = await your_module.locales()
but, considering there is a function Expo.DangerZone.Localization.getCurrentLocaleAsync() are you sure a synchronous version, getCurrentLocaleSync() or getCurrentLocale() don't exist? That would make this much easier you could just call the function directly and obtain the value.