item.match is not a function in React Native - react-native

im having this error every time i type even one letter in my search bar and i dont know how to fix. sorry noob dev
const [dataList] = useState(data)
const [filtered, setFiltered] = useState(dataList);
const onSearch = (text) => {
if (text) {
const temp = text.toLowerCase();
const tempList = dataList.filter(item => {
if (item.match(temp))
return item
})
setFiltered(tempList);
setSearching(true);
}
else {
setFiltered(dataList);
setSearching(false);
}
};
here is the error i get

hi maybe item is not a String, it needs to be.
and another syntax advice.
change to return item.match(temp)

Related

Display date from Firestore React native

I try to display the picked event date för my posts from Firestore using moment. Right now it just print The current day, so I display the date but not ont he right way. I get no error message. I have tried to change the timestamp to "dateUpload". but it gives me a print in my Text component "invalid date". Do any have clue of what I can do?
This is how display it my flatlist:
postDate={moment(item.timestamp).format("ll")}
In my redux Action.js
export function fetchFollowingUsersPosts(uid) {
return ((dispatch, getState) => {
firebase.firestore()
.collection("posts")
.doc(uid)
.collection("userPosts")
.orderBy("creation", "asc")
.get()
.then((snapshot) => {
const uid = snapshot.query.EP.path.segments[1];
const user = getState().usersState.users.find(el => el.uid === uid);
const posts = snapshot.docs.map((doc) => {
const { data: firebaseTimestamp, ...rest } = doc.data()
const id = doc.id;
const data = firebaseTimestamp ? moment(firebaseTimestamp.toDate()) : null
return {
...rest,
id,
user,
...data
}
})
//console.log(posts);
dispatch({ type: USERS_POSTS_STATE_CHANGE, posts, uid, })
})
})
}
Image on my database:
Instead of const data = firebaseTimestamp ? moment(firebaseTimestamp.toDate()) : null, try this const data = firebaseTimestamp ? firebaseTimestamp.toDate() : null , so you'll be having a javascript Date object, instead of a Moment object.
Then, you can use it as you did postDate={moment(item.timestamp).format("ll")}, assuming that item.timestamp is the Date object from above

fetch pictures with mongoose with a certain parameter

Hi and thanks for all the people willing and ready to help me out !
I have a mongoose Model like so :
const pictureSchema = mongoose.Schema ({
pictureName : String,
creator : String,
description : String,
img : String,
createdAt : {
type : Date,
default : new Date(),
},
themeLinked : String
})
Now what i am trying to do, is to fetch all the documents that have a certain specific value for "themeLinked". it's like sorting all the entries in my documents that have the same "themeLinked".
so what i did, from my front-end react App, i sent the value of theme linked as a req.param. so it is sent to my back end with the GET request.
and in my back end, in the controller i wrote this code :
const fetchPictures = async (req,res) => {
const {themeId} = req.params;
try {
const pictures = await pictureModel.findOne({themeLinked : themeId});
res.status(200).json(pictures)
} catch (err) {
res.status(404).json({ message : err})
}
}
and in the network Tab in my chrome browser, i get 'null' as a value for Response.
so beeing a begginer i am struggling to find the right way to fetch all the pictures that have the same 'themeLinked' value....this must be pretty simple but i'm struggling
thanks !!
ok i got, it, all i needed to do was :
const fetchPictures = async (req,res) => {
const {themeId} = req.params;
try {
const pictures = await pictureModel.find({themeLinked : themeId});
res.status(200).json(pictures)
} catch (err) {
res.status(404).json({ message : err})
}
}
for Obvious lexical reasons, findOne only returns one entry, as find returns all entries that have the same matching 'themeLinked' value....:)

i18n won't translate correctly when inside array or object in React Native

I'm trying to use i18n-js to translate some strings into other languages. If I have my code in normal code, it works. Ex:
//Displays "Something" (no quotes) where I want it
<Text> translate("Something"); </Text>
But if I put it inside an array or object, then call it later, it stops working and shows a missing message instead of the text I want translated. Ex:
const messages = {
something: translate("Something"),
// other translations...
}
// later on
// Displays "[missing "en.Something" translation]" (no quotes) where I want it
<Text> messages.something </Text>
The following is my code for my translate function, as well as the config for i18n. I'm using lodash-memoize, but that is unrelated to the issue. I've already checked that the text being passed to i18n.t() is the same (including type) no matter if it's in normal code or in the array, but it still doesn't return the correct thing. I have some error checking written up to avoid getting the missing message on screen, but that still doesn't fix the issue that it can't find the translation.
export const translationGetters = ({
en: () => require('./translations/en.json'),
es: () => require('./translations/es.json')
});
export const translate = memoize(
(key, config) => {
text = i18n.t(key, config)
return text
},
(key, config) => (config ? key + JSON.stringify(config) : key)
);
export const setI18nConfig = () => {
// fallback if no available language fits
const fallback = { languageTag: "en", isRTL: false };
const { languageTag, isRTL } =
RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
fallback;
// clear translation cache
translate.cache.clear();
// update layout direction
I18nManager.forceRTL(isRTL);
// set i18n-js config
i18n.translations = { [languageTag]: translationGetters[languageTag]() };
i18n.locale = languageTag;
};
I have no idea where to go on this. Any advice would be appreciated!
Same problem here, workaround is to return array/object from inside a function:
Don't work
export const translations = [i18.t('path')]
Works
export function getTranslations() {
const translations = [i18.t('path')]
return translations
}

When state changes for graphql variable, result stays the same on react-native

I'm trying to create an app using shopify graphql api to create an ecommerce app on react native expo.
I have an onPress that calls a setState to change the state of the graphQL variable but the results don't change from the initial state of 'currentSubCategories'
const [currentSubCategories, setSubCategories] = useState(Categories[0].subCategory[0].handle);
let {
collection,
loading,
hasMore,
refetch,
isFetchingMore,
} = useCollectionQuery(currentSubCategories, first, priceRange);
const [currentCategory, setCategory] = useState({categories: Categories[0]});
const onSubCategorySelect = (subCategory) => { setSubCategories(subCategory.handle) }
onPress={() => onSubCategorySelect(item)}
function useCollectionQuery(
collectionHandle: string,
first: number,
priceRange: [number, number],
) {
let [isInitFetching, setInitFetching] = useState<boolean>(true);
let [isReloading, setIsReloading] = useState<boolean>(true);
let [collection, setCollection] = useState<Array<Product>>([]);
let isFetchingMore = useRef<boolean>(false);
let hasMore = useRef<boolean>(true);
let defaultCurrency = useDefaultCurrency().data;
let { data, loading, refetch: refetchQuery } = useQuery<
GetCollection,
GetCollectionVariables
>(GET_COLLECTION, {
variables: {
collectionHandle,
first,
sortKey: ProductCollectionSortKeys.BEST_SELLING,
presentmentCurrencies: [defaultCurrency],
},
notifyOnNetworkStatusChange: true,
fetchPolicy: 'no-cache',
});
let getMoreUntilTarget = async (
targetAmount: number,
cursor: string | null,
handle: string,
filter: [number, number],
) => {
let result: Array<Product> = [];
let moreData: Array<Product> = [];
let { data } = await refetchQuery({
first,
collectionHandle: handle,
after: cursor,
});
...
useEffect(() => {
if (!loading) {
isFetchingMore.current = false;
}
if (isInitFetching && !!data && !!data.collectionByHandle) {
let newCollection = mapToProducts(data.collectionByHandle.products);
hasMore.current = !!data.collectionByHandle?.products.pageInfo
.hasNextPage;
setCollection(newCollection);
setIsReloading(false);
setInitFetching(false);
}
}, [loading, isInitFetching]); // eslint-disable-line react-hooks/exhaustive-deps
return {
collection,
loading: isReloading,
hasMore: hasMore.current,
isFetchingMore: isFetchingMore.current,
refetch,
};
}
I'm using flatList to show the result
<FlatList
data={collection}
renderItem={({ item }) => (
<Text>{item.title}</Text>
)}
/>
According to docs you have to pass new variables to refetch otherwise refetch will use initial values.
In this case (custom hook) you have 2 ways to solvethis problem:
return variables from your custom hook (taken from useQuery),
return some own refetch function.
1st option needs 'manual' variables updating like:
refetch( { ...variablesFromHook, collectionHandle: currentSubCategories } );
In 2nd case you can create myRefetch (and return as refetch) taking collectionHandle parameter to call refetch with updated variables - hiding 'complexity' inside your hook.
Both cases needs refetch call after updating state (setSubCategories) so you should use this refetch inside useEffect with [currentSubCategories] dependency ... or simply don't use state, call refetch directly from event handler (in onSubCategorySelect).

Adding and removing items in AsyncStorage

Looking to add some items, display a list then be able to delete each item separately, my understanding of this problem is that I have to create an array then update it each time I want to delete an item then save. That seems quite complex for a basic db operation, I tried several approachs don't know if my code is what I'm supposed to do. Can someone please point to the right direction?
The last error I'm facing:
Object is null or undefined from
C:\Users\oled\stock\node_modules\react-native\Libraries\polyfills\Array.es6.js:24:26
_toConsumableArray
FetchValue = () => {
AsyncStorage.getItem("Favorites").then((value) => {
this.setState({
favs: JSON.parse(value)
});
}).done();
};
SaveValue = () => {
const newFavs = [...this.state.favs, this.state.UserInput];
this.setState({ favs: newFavs, UserInput: '' }, () => {
AsyncStorage.setItem("Favorites", JSON.stringify(this.state.favs));
Keyboard.dismiss()
});
};
RemoveValue(item){
const index = this.state.favs.indexOf(item);
const newArray = [...this.state.favs];
newArray.splice(index,1);
this.setState({ favs: newArray });
AsyncStorage.setItem("Favorites", JSON.stringify(newArray));
}
Full code : https://pastebin.com/p7sbQTNG
I think after removing last element, your array is empty. So after that whenever you try to remove the value from array it will give you the error. So please check the condition where array count is greater than 0 or not.
I hope it will work for you.
replace your RemoveValue method with this code.
We need to check if the item is not null/undefined
RemoveValue(item){
if(item !== null && item !== undefined){
const index = this.state.favs.indexOf(item);
const newArray = [...this.state.favs];
newArray.splice(index,1);
this.setState({ favs: newArray });
AsyncStorage.setItem("Favorites", JSON.stringify(newArray));
}
this will resolve your crash.