calling a function from a const value - javascript

I have an initial state const item that looks like this:
const INITIAL_STATE = {
endPoint: { street: '', coordinates: [] }, //[13.3969, 52.5182]
startingPoint: { street: '', coordinates: [] }, //[13.413215, 52.521918]
favouritePoint: { street: '', coordinates: [] },
favouriteLocations: {getFavouritePlaces()},
// favouriteLocations: [
// {
// name: 'Zu Hause',
// street: 'Müllersweg',
// coordinates: [8.217462, 53.13975], //[8.258844, 53.119525],
// },
// {
// name: 'Büro',
// street: 'Philipp-Reis-Gang',
// coordinates: [8.258844, 53.119525], //[8.217462, 53.13975],
// },
// {
// name: 'KaffeeHaus',
// street: 'Cloppenburgerstr.',
// coordinates: [8.211, 53.113],
// },
// ],
addressesFoundList: [],
};
Instead of the hardcoded value, I am trying to call a function for favouriteLocations that will return an object of the same type. However, currently this does not call my function.
My function looks like this:
const getFavouritePlaces = () => {
return ...
}
Later on, I will be using this initial state for my redux setup.

I don't think you need the brackets around the function call.
Change favouriteLocations: {getFavouritePlaces()}, To favouriteLocations: getFavouritePlaces(),.

As mentioned there's syntax error.
Alternativ 1 - Spreading the function containing the desired object:
const INITIAL_STATE = {
favouriteLocations: {...getFavouritePlaces()}
};
Alternativ 2 - Run the function that will return the desired object:
const INITIAL_STATE = {
favouriteLocations: getFavouritePlaces()
};

You should declare it like this:
const getFavouritePlaces = () => {
console.log('test');
}
const INITIAL_STATE = {
favouriteLocations: getFavouritePlaces
}
INITIAL_STATE.favouriteLocations();
This will work even if your fucntion recevies a variable like:
const getFavouritePlaces = (x) => {
console.log(x);
};
const INITIAL_STATE = {
favouriteLocations: getFavouritePlaces
}
INITIAL_STATE.favouriteLocations('test');

Related

Create new object from array

I'm trying to create new object with different properties name from Array.
Array is:
profiles: Array(1)
0:
column:
name: "profileName"
title: "Profile name"
status: "Active"
I want to create new function that return object with two properties:
id: 'profileName',
profileStatus: 'Active'
The function that I have create is returning only one property as undefined undefined=undefined.
function getProfile(profiles) {
if (!profiles.length) return undefined;
return profiles.reduce((obj, profile) => {
console.log('profiles', profile);
return ({
...obj,
id: profile.column.name,
profileStatus: profile.status,
});
}, {});
}
The function getProfile is taking as input array 'profiles' from outside,
I've just tested here and this seems to be working actually
const getProfile1 = (p) => p.reduce((obj, profile) =>({
...obj,
id: profile.column.name,
profileStatus: profile.status,
}), {});
You can use map as an alternative.
var profiles = [{"column":{"name": "profileName3","title": "3Profile name"},"status": "Active"},{"column":{"name": "profileName","title": "Profile name"},"status": "Active"}];
function getProfile(profiles) {
if (!profiles.length) return undefined;
return profiles.map(function(profile,v){
return {id:profile.column.name,profileStatus: profile.status};
});
}
console.log(getProfile(profiles));
Whenever I use reduce in this way, I usually index the final object by some sort of an id. As noted in another answer, you could use map in this situation as well. If you really want your final data structure to be an object, however, you could do something like this:
/**
* returns object indexed by profile id
*/
const formatProfiles = (profiles) => {
return profiles.reduce((obj, profile) => {
return {
...obj,
[profile.id]: {
id: profile.column.name,
profileStatus: profile.status,
}
};
}, {});
};
const profiles = [
{
id: 0,
status: 'active',
column: {
name: "profile_name_1",
title: "profile_title_1",
},
},
{
id: 1,
status: 'inactive',
column: {
name: "profile_name_2",
title: "profile_title_2",
}
}
];
const result = formatProfiles(profiles);
/**
* Result would look like this:
*/
// {
// '0': { id: 'profile_name_1', profileStatus: 'active' },
// '1': { id: 'profile_name_2', profileStatus: 'inactive' }
// }

Updating the values in an array of objects in react js

I am trying to merge two objects that I am getting from 2 different api calls(the example here is just a sample). How can I merge the UserId array of object and the userCredentials array together in the user state? I want the state to look like this user:[{id: 1, name"john", country="de"},{id: 2, name"micheal", country="us"}]
...
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
user: []
};
}
componentDidMount() {
//api call 1 receiving user Id and name
const UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
this.setState({ user: UserId });
//api call 2 receiving userCredentials
const userCredentials = [
{ id: 1, country: "de" },
{ id: 1, country: "us" }
];
this.setState({
user: { ...this.state.user, credentials: userCredentials }
});
}
render() {
console.log("values", this.state);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
</div>
);
}
}
...
my sample code is
https://codesandbox.io/s/fancy-water-5lzs1?file=/src/App.js:0-754
Basically you need to map thru 1 array and find if each object in the array exists in another array and use spread operator and return the merged object in map callback
Working demo
Use the code below:
// option 1 - if you know the keys of the object
let merged = UserId.map(u => {
const user = userCredentials.find(uc => uc.id === u.id);
if (user) u["country"] = user.country;
return u;
});
// option 2 - generic merge
let merged2 = UserId.map(u => {
const user = userCredentials.find(uc => uc.id === u.id);
if (user) return { ...u, ...user };
return u;
});
You could use 'array.concat([])' to merge two array objects together. See bellow example.
let UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
const userCredentials = [{ id: 1, country: "de" },{ id: 1, country: "us" }];
const newArray = UserId.concat(userCredentials);
Since you have defined UserId as a const you cannot change it. So you have to make it to let or var to modify the variable.

How to properly reset Vue Composition Api's reactive values

I'm wondering how should I reset a reactive in vuejs setup? (i know if change it to the ref and using view.value will solve this problem, but there should be an answer to this for using reactive)
setup(props, context){
// states
const DataTable = reactive((null as unknown) as DataTable);
const PolicyForm = reactive((null as unknown) as PolicyForm);
let view = reactive(resetViewState());
let config = reactive(
(resetPreRegisterConfig() as unknown) as PreRegisterConfig
);
// methods:
const fetchProfilelist = (
pagination: Pagination{ page:1, size:15},
sort_label: string = ""
) => {
DataTable.fetchTablelist(api_fetchProfilelist, pagination, sort_label);
};
const pageRefresh = () => {
view = resetViewState(); // 👈
config = resetPreRegisterConfig();
fetchProfilelist();
};
return {
DataTable,
PolicyForm,
view,
config,
fetchProfilelist,
pageRefresh
}
You can use Object.assign:
setup() {
const initialState = {
name: "",
lastName: "",
email: ""
};
const form = reactive({ ...initialState });
function resetForm() {
Object.assign(form, initialState);
}
function setForm() {
Object.assign(form, {
name: "John",
lastName: "Doe",
email: "john#doe.com"
});
}
return { form, setForm, resetForm };
}
See it live on codesandbox
credits: taken from here
Object.assign didn't work for me. (Maybe because I used a shim for the Composition API in Nuxtjs 2?) For anybody that run into the same problem: I had to use a compact loop.
setup() {
const initialState = {
name: "",
lastName: "",
email: ""
};
const form = reactive({ ...initialState });
function resetForm() {
for (const [key, value] of Object.entries(initialState)) {
form[key] = value
}
}
function setForm(values = {name: "John", lastName: "Doe", email: "john#doe.com"}) {
// only loop with the supported keys of initial state
for (const key of Object.keys(initialState)) {
form[key] = values[key]
}
}
return { form, setForm, resetForm };
}
Citing from the official Vueland Discord server:
"For what I know, reactive is the old way we use to do reactivity from the Classic API, so to reset the values should be something like:"
const myData = reactive({
foo: true,
bar: ''
})
function resetValues () {
myData.foo = true
myData.bar = ''
}
Therefore, if you don't change properties you should be able to use Object.assign(). (Correct me if I'm wrong)
How about use ref instead of reactive?
const myData = ref({ xxx: 11 })
// ... After many operations on myData
// resetData
myData.value = { xxx: 11 }
The disadvantage is that you need to add .value when using it in script.
But this is the same as reactive in vue template.
If you have deep objects you can use this trick to reset the values converting them to JSON
setup(){
const form = ref({
order: '',
user:{},
});
const defaultForm = JSON.parse(JSON.stringify(form));
form.value.user = {firstname:"Joe", lastname:"Doe"};
const onSubmit = () => {
// Reset values to default
form.value = JSON.parse(JSON.stringify(defaultForm));
}
}
If you do not want to use ref and want to reset value of a reactive variable then you have to take one key variable for reference in the reactive variable, because reinitializing reactive variable directly will cause to loose reactivity in the process.
So to reset the value use extra key variable in reactive variable, see code as below
setup() {
const initialState = {
name: "",
email: ""
};
const form = reactive({ data: ...initialState });
function resetForm() {
form.data = { ...initialState };
}
function setForm() {
form.data = {
name: "Bahubali",
email: "bahubali#mahismati.com"
});
}
return { form, setForm, resetForm };
}
So basically you are taking data as key of your reactive variable and when you want to reset or set your values you just need to change the form.data and it will be reactive and refreshes the elements which uses form.data.

Mongoose.model('model_name') return empty object when function is required in the mongoose model schema file

I apologize if the title of the question is misleading, because I am not too sure how to explain this. I have 2 files, matchedTransaction.js and player.js.
sharedApi/player.js
const MatchedTransactionModel = require('../models/matchedTransaction');
// #1: If I try to console log here, the output will be an empty object "{}"
console.log(MatchedTransactionModel);
async function banPlayer(userId) {
// ...
// Because MatchedTransactionModel is an empty object,
// the code below will crash with the following error:
// "MatchedTransactionModel.findOne is not a function"
const pendingMatchedTransaction = await MatchedTransactionModel.findOne({
$and: [
{
$or: [
{ reserverAccountId: `${account._id}` },
{ sellerAccountId: `${account._id}` },
],
},
{
$or: [
{ status: 'pendingReserverPayment' },
{ status: 'pendingSellerConfirmation' },
],
},
],
});
// ...
}
module.exports = {
banPlayer,
};
models/matchedTransaction.js
const mongoose = require('mongoose');
const { banPlayer } = require('../sharedApi/player');
const MatchedTransactionSchema = new mongoose.Schema([
{
createdDate: {
type: Date,
required: true,
},
// ...
},
]);
MatchedTransactionSchema.post('init', async function postInit() {
// ...
await banPlayer(userId);
});
const MatchedTransactionModel = mongoose.model('matchedTransactions', MatchedTransactionSchema);
module.exports = MatchedTransactionModel;
Notice that in player.js when I tried to console.log the required MatchedTransactionModel, it returns an empty object. However, if I made the following changes to matchedTransaction.js:
models/matchedTransaction.js
// Instead of requiring banPlayer outside, I only require it when it is used
// const { banPlayer } = require('../sharedApi/player');
MatchedTransactionSchema.post('init', async function postInit() {
// ...
const { banPlayer } = require('../sharedApi/player');
await banPlayer(userId);
});
// ...
The output of the previously mentioned console.log will be a non-empty object, and MatchedTransactionModel.findOne is working as expected.
Why does that happen?
The only problem I see with your code is that when you define the schema on matchedTransaction.js, you passed an array which I think is problematic and does not make sense. You must pass an object there:
const MatchedTransactionSchema = new mongoose.Schema({
createdDate: {
type: Date,
required: true,
},
// ...
});

Verify if content key Json has exist using Vue

I want to know how to check if "novalue" exist
For example:
{
name: "maria",
city_id: "novalue"
....
}
How i do this in Vue?
Do it in <div v-if="condition"> or function?
In case you want to/can use ES7 features:
const containsKey = (obj, key ) => Object.keys(obj).includes(key);
Implementation example:
const someCoolObject = {name: 'Foo', lastName: 'Bar'};
const hasName = containsKey(someCoolObject, 'name');
const hasNickName = containsKey(someCoolObject, 'hasNickName');
console.log(hasName, hasNickName); // true, false
For Vue:
Component:
{
methods: {
containsKey(obj, key ) {
return Object.keys(obj).includes(key);
}
},
computed: {
hasName() {
return this.containsKey(this.someObject, 'name');
}
}
}
Template:
<div v-if="hasName"></div>

Categories

Resources