typeError object(...) is not a function - vue.js

I get the "object is not a function" error on the line where the "setup()" function appears.
I have no clue how to debug this... Am I doing something wrong? (I'm not an experimented developer, so I know I'm doing things wrong, but here, I have no clue what it is...)
It's asking me to add more details because my post is mainly code... So I'm writing this, but I habe idea what details I could c=possibly add. :-)
Thanks in advance for your help!!
<script>
import { ref } from 'vue'
import Ftable from '#/components/tables/Ftable.vue'
import Searchbar from '#/components/tables/Searchbar.vue'
import getMainCollection from '#/composables/getMainCollection'
export default {
name: 'Home',
components: { Searchbar, Ftable },
setup(){ //error arrives on this line
const { getData, getMore } = getMainCollection()
const documents = ref('')
const lastVisible = ref('')
const type = ref('')
const country = ref('')
function newSearch() {
const {doc, last} = getData(type, country)
documents.value = doc
lastVisible.Value = last
}
function askForMore() {
const { doc, last } = getMore(type, country, lastVisible)
documents.value = doc
lastVisible.value = last
}
return { documents, askForMore, newSearch, askForMore }
}
}
</script>
import { ref } from 'vue'
import { projectFirestore } from '#/firebase/config'
const getMainCollection = () => {
const collectionGroupRef = projectFirestore.collectionGroup('users')
const lastVisible = ref('')
const documents = ('')
function getData(type, country) {
const filter = null
if (type != null && country == null){
filter = collectionGroupRef.where('type', '==', `${type}`)
}
else if(type == null && country != null){
filter = collectionGroupRef.where('country', '==', `${country}`)
}
else{
filter = collectionGroupRef
}
const data = filter.orderBy('createdAt')
.limit(2)
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
documents.value.push({ ...doc.data(), id: doc.id})
})
lastVisible = querySnapshot.docs[querySnapshot.docs.length-1]
})
return( documents, lastVisible)
}
function getMore(type, country, lastVisible) {
const filter = null
if (type != null && country == null){
filter = collectionGroupRef.where('type', '==', `${type}`)
}
else if(type == null && country != null){
filter = collectionGroupRef.where('country', '==', `${country}`)
}
else{
filter = collectionGroupRef
}
filter.startAfter(lastVisible)
.limit(2)
.orderBy(createdAt)
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
documents.value.push({ ...doc.data(), id: doc.id })
})
lastVisible = querySnapshot.docs[querySnapshot.docs.length-1]
})
return( documents, lastVisible)
}
return ( getData, getMore )
}
export { getMainCollection }

Since you exported getMainCollection as an object:
export { getMainConnection }
You need to destructure it when importing:
import { getMainCollection } from '#/composables/getMainCollection'

Related

How do I resolve a callback error with 'callback' is an instance of Object)?

TypeError: callback is not a function. (In 'callback(data)',
'callback' is an instance of Object)
The code here works just fine when I write it like this:
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
// { categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
When i uncomment that other line, it breaks and gives me this error.
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
{ categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
Here is the relevant snippet from listingsAPI (below) if it helps but this code works fine when there is only one object. Is there a specific way to make this work with two objects like above?
if (categoryId) {
return (
listingsRef
.where('categoryID', '==', categoryId)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
if (categoryId2) {
return (
listingsRef
.where('categoryID2', '==', categoryId2)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
You can combine your queries via this way if you want to have it optional:
let query = listingsRef.where('isApproved', '==', isApproved)
if (categoryId) {
query = query.where('categoryID', '==', categoryId)
}
if (categoryId2) {
query = query.where('categoryID2', '==', categoryId2)
}
query.onSnapshot...

How to change the width of NormalPeoplePicker dropdown

I'm using default example of NormalPeoplePicker from https://developer.microsoft.com/en-us/fluentui#/controls/web/peoplepicker#IPeoplePickerProps.
When the dropdown displays it cuts off longer items (example: 'Anny Lundqvist, Junior Manager of Soft..'). How do I make it wider, so that the full item's text displays?
import * as React from 'react';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import { IPersonaProps } from 'office-ui-fabric-react/lib/Persona';
import { IBasePickerSuggestionsProps, NormalPeoplePicker, ValidationState } from 'office-ui-fabric-react/lib/Pickers';
import { people, mru } from '#uifabric/example-data';
const suggestionProps: IBasePickerSuggestionsProps = {
suggestionsHeaderText: 'Suggested People',
mostRecentlyUsedHeaderText: 'Suggested Contacts',
noResultsFoundText: 'No results found',
loadingText: 'Loading',
showRemoveButtons: true,
suggestionsAvailableAlertText: 'People Picker Suggestions available',
suggestionsContainerAriaLabel: 'Suggested contacts',
};
const checkboxStyles = {
root: {
marginTop: 10,
},
};
export const PeoplePickerNormalExample: React.FunctionComponent = () => {
const [delayResults, setDelayResults] = React.useState(false);
const [isPickerDisabled, setIsPickerDisabled] = React.useState(false);
const [mostRecentlyUsed, setMostRecentlyUsed] = React.useState<IPersonaProps[]>(mru);
const [peopleList, setPeopleList] = React.useState<IPersonaProps[]>(people);
const picker = React.useRef(null);
const onFilterChanged = (
filterText: string,
currentPersonas: IPersonaProps[],
limitResults?: number,
): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (filterText) {
let filteredPersonas: IPersonaProps[] = filterPersonasByText(filterText);
filteredPersonas = removeDuplicates(filteredPersonas, currentPersonas);
filteredPersonas = limitResults ? filteredPersonas.slice(0, limitResults) : filteredPersonas;
return filterPromise(filteredPersonas);
} else {
return [];
}
};
const filterPersonasByText = (filterText: string): IPersonaProps[] => {
return peopleList.filter(item => doesTextStartWith(item.text as string, filterText));
};
const filterPromise = (personasToReturn: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (delayResults) {
return convertResultsToPromise(personasToReturn);
} else {
return personasToReturn;
}
};
const returnMostRecentlyUsed = (currentPersonas: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
return filterPromise(removeDuplicates(mostRecentlyUsed, currentPersonas));
};
const onRemoveSuggestion = (item: IPersonaProps): void => {
const indexPeopleList: number = peopleList.indexOf(item);
const indexMostRecentlyUsed: number = mostRecentlyUsed.indexOf(item);
if (indexPeopleList >= 0) {
const newPeople: IPersonaProps[] = peopleList
.slice(0, indexPeopleList)
.concat(peopleList.slice(indexPeopleList + 1));
setPeopleList(newPeople);
}
if (indexMostRecentlyUsed >= 0) {
const newSuggestedPeople: IPersonaProps[] = mostRecentlyUsed
.slice(0, indexMostRecentlyUsed)
.concat(mostRecentlyUsed.slice(indexMostRecentlyUsed + 1));
setMostRecentlyUsed(newSuggestedPeople);
}
};
const onDisabledButtonClick = (): void => {
setIsPickerDisabled(!isPickerDisabled);
};
const onToggleDelayResultsChange = (): void => {
setDelayResults(!delayResults);
};
return (
<div>
<NormalPeoplePicker
// eslint-disable-next-line react/jsx-no-bind
onResolveSuggestions={onFilterChanged}
// eslint-disable-next-line react/jsx-no-bind
onEmptyInputFocus={returnMostRecentlyUsed}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={suggestionProps}
className={'ms-PeoplePicker'}
key={'normal'}
// eslint-disable-next-line react/jsx-no-bind
onRemoveSuggestion={onRemoveSuggestion}
onValidateInput={validateInput}
removeButtonAriaLabel={'Remove'}
inputProps={{
onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),
'aria-label': 'People Picker',
}}
componentRef={picker}
onInputChange={onInputChange}
resolveDelay={300}
disabled={isPickerDisabled}
/>
<Checkbox
label="Disable People Picker"
checked={isPickerDisabled}
// eslint-disable-next-line react/jsx-no-bind
onChange={onDisabledButtonClick}
styles={checkboxStyles}
/>
<Checkbox
label="Delay Suggestion Results"
defaultChecked={delayResults}
// eslint-disable-next-line react/jsx-no-bind
onChange={onToggleDelayResultsChange}
styles={checkboxStyles}
/>
</div>
);
};
function doesTextStartWith(text: string, filterText: string): boolean {
return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
}
function removeDuplicates(personas: IPersonaProps[], possibleDupes: IPersonaProps[]) {
return personas.filter(persona => !listContainsPersona(persona, possibleDupes));
}
function listContainsPersona(persona: IPersonaProps, personas: IPersonaProps[]) {
if (!personas || !personas.length || personas.length === 0) {
return false;
}
return personas.filter(item => item.text === persona.text).length > 0;
}
function convertResultsToPromise(results: IPersonaProps[]): Promise<IPersonaProps[]> {
return new Promise<IPersonaProps[]>((resolve, reject) => setTimeout(() => resolve(results), 2000));
}
function getTextFromItem(persona: IPersonaProps): string {
return persona.text as string;
}
function validateInput(input: string): ValidationState {
if (input.indexOf('#') !== -1) {
return ValidationState.valid;
} else if (input.length > 1) {
return ValidationState.warning;
} else {
return ValidationState.invalid;
}
}
/**
* Takes in the picker input and modifies it in whichever way
* the caller wants, i.e. parsing entries copied from Outlook (sample
* input: "Aaron Reid <aaron>").
*
* #param input The text entered into the picker.
*/
function onInputChange(input: string): string {
const outlookRegEx = /<.*>/g;
const emailAddress = outlookRegEx.exec(input);
if (emailAddress && emailAddress[0]) {
return emailAddress[0].substring(1, emailAddress[0].length - 1);
}
return input;
}
Component which renders suggestion list have fixed width of 180px. Take a look at PeoplePickerItemSuggestion.styles.ts.
What you can do is to modify this class .ms-PeoplePicker-Persona:
.ms-PeoplePicker-Persona {
width: 260px; // Or what ever you want
}
UPDATE - Solution from comments
Change width trough styles property of PeoplePickerItemSuggestion Component
const onRenderSuggestionsItem = (personaProps, suggestionsProps) => (
<PeoplePickerItemSuggestion
personaProps={personaProps}
suggestionsProps={suggestionsProps}
styles={{ personaWrapper: { width: '100%' }}}
/>
);
<NormalPeoplePicker
onRenderSuggestionsItem={onRenderSuggestionsItem}
pickerCalloutProps={{ calloutWidth: 500 }}
...restProps
/>
Working Codepen example
For more information how to customize components read Component Styling.

React Native Redux issue

I am having an issue with adding favourite functionality for e-commerce app. Getting error of undefined.enter image description here
case TOGGLE_FAVOURITE:
const exitsIndex = state.favouriteProducts.findIndex((meal) => meal.id === action.productId);
if(exitsIndex >= 0) {
return { ...state, favouriteProducts: state.favouriteProducts.filter((meal) => meal.id !== action.productId) }
} else {
const favMeal = state.availableProducts.find((meal) => meal.id === action.productId);
return { ...state, favouriteProducts: state.favouriteProducts.concat(favMeal) };
}
This is my action:
export const toggleFavourite = id => {
return { type: TOGGLE_FAVOURITE, productId: id };
};
And this is my call function:
const toggleFavouriteHandler = useCallback(() => {
dispatch(toggleFavourite(productId));
}, [dispatch, productId]);
you have to check for the initial state, when you are doing findIndex on favouriteProducts , favouriteProducts is null.
so just check if
state.favouriteProducts === null and that should work
To prevent TypeError you should check if state.favouriteProducts is undefined or null.
In this case, i would use:
case TOGGLE_FAVOURITE:
if (!state.favouriteProducts) return false; // you need this
const exitsIndex = state.favouriteProducts.findIndex((meal) => meal.id === action.productId);
if (exitsIndex >= 0) {
return { ...state, favouriteProducts: state.favouriteProducts.filter((meal) => meal.id !== action.productId) }
} else {
const favMeal = state.availableProducts.find((meal) => meal.id === action.productId);
return { ...state, favouriteProducts: state.favouriteProducts.concat(favMeal) };
}
I found different solution. Now its working
case TOGGLE_FAVOURITE:
const addedFavourite = action.product;
const id = addedFavourite.id;
const product_name = addedFavourite.product_name;
const product_image = addedFavourite.product_image;
const product_description = addedFavourite.product_description;
const product_price = addedFavourite.product_price;
const category_id = addedFavourite.category_id;
let updatedFavouriteItem = new Product(
id,
product_name,
product_image,
product_description,
product_price,
category_id,
)
if(state.items[addedFavourite.id] != null){
let updatedCartItems = { ...state.items };
delete updatedCartItems[action.product.id];
return {
...state,
items: updatedCartItems,
}
}
return{
...state,
items: {...state.items, [addedFavourite.id]: updatedFavouriteItem }
}
}
return state;
}

integrate vue-i18n in vue-beautiful-chat

I try to integrate (vue-i18n) at this library (https://github.com/mattmezza/vue-beautiful-chat) in src folder but I have some integration problems
so,
in this file ./i18n/translations.js => we have the translations
in src/index.js
import Launcher from './Launcher.vue'
import VTooltip from 'v-tooltip'
import VueI18n from 'vue-i18n'
import messages from './i18n/translations.js'
const defaultComponentName = 'beautiful-chat'
const Plugin = {
install (Vue, options = {}) {
/**
* Makes sure that plugin can be installed only once
*/
if (this.installed) {
return
}
Vue.use(VueI18n)
const locale = navigator.language
const i18n = new VueI18n({
fallbackLocale: 'fr',
locale: locale,
messages
})
this.installed = true
this.event = new Vue({i18n})
this.dynamicContainer = null
this.componentName = options.componentName || defaultComponentName
/**
* Plugin API
*/
Vue.prototype.$chat = {
_setDynamicContainer (dynamicContainer) {
Plugin.dynamicContainer = dynamicContainer
}
}
/**
* Sets custom component name (if provided)
*/
Vue.component(this.componentName, Launcher)
Vue.use(VTooltip)
Vue.use(VueI18n)
}
}
export default Plugin
And i start to change in the file "src/Launcher.vue" "you" in the header of the chat
computed: {
chatWindowTitle() {
if (this.title !== '') {
return this.title
}
if (this.participants.length === 0) {
return $t('participant.you_only')
} else if (this.participants.length > 1) {
return $t('participant.you_and_participants', { participant: 'this.participants[0].name' })
} else {
return 'You & ' + this.participants[0].name
}
}
},
but i receive this error
i have try few others methods as this.$i18n and others.
Can you help me please ?
Thanks a lot.
Are you possible missing the "this" when referring to "$t" on the computed property?
computed: {
chatWindowTitle() {
if (this.title !== '') {
return this.title
}
if (this.participants.length === 0) {
return this.$t('participant.you_only')
} else if (this.participants.length > 1) {
return this.$t('participant.you_and_participants', { participant: 'this.participants[0].name' })
} else {
return 'You & ' + this.participants[0].name
}
}
},

React Native SectionList (title, data) - Search in the data field

I am trying to build Search function in SectionList. I have search inside the 'data' (second field) and not inside 'title' but I am not able to make it work.
My Data is about the Flat / resident details of an Apartment -
sectiondata =
[{"title":"GROUND FLOOR",
"data":[
{"id":"48","res_type":"owner","user_name":"Ashwani","flat_id":"1","flat_name":"001","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"98855550"},
{"id":"49","res_type":"owner","user_name":"Rahul","flat_id":"2","flat_name":"002","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"999999"}
]
}]
I am trying something like this but it is not working.
searchFilterFunction = (text) => {
let search = text.toLowerCase();
this.setState({
check: this.state.sectiondata.filter(
obj => obj.data['flat_name'].toLowerCase().includes(search))
});
}
How to filter data base on name? Please assist here.
Thanks.
You can try to search like this:
onChangeText(text) {
if (text.trim().length > 0) {
var temp = []
sectiondata.map((item) => {
var dataItem = {};
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.brandData = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})
} else {
this.setState({
sectiondata: this.state.tempData
})
}
}
searchFilterFunction(text) {
if( text == undefined || text == '') {
this.setState({
sectiondata: this.arrayholder
})
return;
}
if (text.trim().length > 0) {
var temp = []
this.state.sectiondata.map((item) => {
var dataItem = {};
var title = item.title;
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.title = title;
dataItem.data = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})