i need to write a search screen. first it shows all posts… · The Chat Archive
Explore / Programming i need to write a search screen. first it shows all posts from my both collections now… Save Share Download ▾ Reporti need to write a search screen. first it shows all posts from my both collections now it doesnt show any results
import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from 'react-native';
import { gStyle } from '../styles/style';
import { Feather } from '@expo/vector-icons';
import React, { useState, useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
export default function Header() {
const [searchTerm, setSearchTerm] = useState('');
const [searchResult, setSearchResult]= useState('');
const handleSearch = async ()=>{
const futureMKSnapshot = await firebase
.firestore()
.collection('FutureMK')
.where('name','>=',searchTerm)
.where('name','<=',searchTerm + '\uf8ff')
.get();
const pastMKSnapshot = await firebase
.firestore()
.collection('PastMK')
.where('name','>=',searchTerm)
.where('name','<=',searchTerm + '\uf8ff')
.get();
const futureMKData = futureMKSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}));
const pastMKData = pastMKSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}));
const results = [...futureMKData, ...pastMKData].filter(item=>
item.name.toLowerCase().includes(searchTerm.toLowerCase()));
setSearchResult(results);
navigation.navigate('Search', { results });
};
const [userAuthenticated, setUserAuthenticated] = useState(false);
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
const hideModal = () => {
setIsModalVisible(false);
};
const navigation = useNavigation();
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUserAuthenticated(true);
} else {
setUserAuthenticated(false);
}
});
return unsubscribe;
}, []);
return (
<View style={gStyle.main}>
<View style={gStyle.headerContainer}>
<Image
source={require('../assets/logo.png')}
style={gStyle.logoImg}
/>
<View style={gStyle.menu}>
<TouchableOpacity onPress={showModal}>
<Text style={gStyle.menuRedLine}></Text>
<Text style={gStyle.menuRedLine}></Text>
<Text style={gStyle.menuRedLine}></Text>
<Modal visible={isModalVisible} animationType='fade' transparent={true}>
<View style={gStyle.modal}>
<TouchableOpacity onPress={hideModal}>
<Text style={gStyle.close}>Х</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('Home')}
>
<Text style={gStyle.menuItem}>Главная</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('AllFutureMK')}
>
<Text style={gStyle.menuItem}>Будущие мастер-классы</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('AllPastMK')}
>
<Text style={gStyle.menuItem}>Архив мастер-классов</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('Sales')}
>
<Text style={gStyle.menuItem}>Скидки</Text>
</TouchableOpacity>
{userAuthenticated ?
<TouchableOpacity
onPress={()=>navigation.navigate('Profile')}
>
<Text style={gStyle.menuItem}>Личный кабинет</Text>
</TouchableOpacity>
:
<TouchableOpacity
onPress={()=>navigation.navigate('Auth')}
>
<Text style={gStyle.menuItem}>Личный кабинет</Text>
</TouchableOpacity>
}
</View>
</Modal>
</TouchableOpacity>
</View>
</View>
<View style={gStyle.searchBox}>
<TextInput style={gStyle.search}
placeholder="Поиск"
onChangeText={(text)=>setSearchTerm(text)}
/>
<View style={gStyle.boxBtn}>
<Pressable style={gStyle.searchBtn}
onPress={handleSearch}
>
<Feather name="search" size={25} color="white" />
</Pressable>
</View>
</View>
</View>
);
AssistantCopy response
There are a couple of issues with your code that may be causing it not to show any results on the search screen:
You're not passing the 'navigation' object to the 'handleSearch' function. You need to either pass it as a parameter or declare it before the function and use it inside the function. Try adding the following before the 'handleSearch' function:
const navigation = useNavigation();
You're not checking if the search term is empty before making the database query. This might be causing the query to return an empty result. Try adding the following check at the beginning of the 'handleSearch' function:
if(!searchTerm.trim()){
setSearchResult([]);
return;
}
This will set 'searchResult' to an empty array and return if the search term is empty or contains only whitespace.
You're not rendering the 'Result' component correctly on the search screen. Change the following line in the 'Search' component:
{results.length > 0 ? (
results.map((item, index)=>
)
): (
Не найдено.
)}
Wow! It actually works! BUt there is still no image):
What do i need to do?
AssistantCopy response
Copy first prompt
Details
Provider openai
Model provenance As recorded by source dataset
Turns 2 (4 messages)
Language —
Added to archive Nov 21, 2026
ID 01m7y2makc3gd1vmmzy9cm99gdSource & license Imported from Suzhen/CodeChat (source ). Imported records earn no Research Points.
Upstream record: 75cb16fa1bbb787dd30b9bc4b20eb626
Suzhen/CodeChat, revision 1681793a6cfb27b68c1f285bd1e78588132bc1c1.
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
here is my collections
FutureMK
import { Text, View, Image, Pressable } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import React, {useState, useEffect} from ‘react’;
import { useNavigation } from ‘@react-navigation/native’;
import {firebase} from ‘…/Firebase/firebase’;
import moment from ‘moment’;
import ‘firebase/compat/storage’;
import ‘firebase/compat/firestore’;
export default function FutureMK({limit}) {
const navigation = useNavigation();
const [futureMKData, setFutureMKData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
let futureMKRef=firebase.firestore().collection(‘FutureMK’).orderBy(‘time’, ‘desc’);
if (limit){
futureMKRef=futureMKRef.limit(limit);
}
const snapshot = await futureMKRef.get();
const data = snapshot.docs.map((doc) => ({id:doc.id, … doc.data()}));
const storage=firebase.storage();
const updatedData = await Promise.all(data.map(async(mkData)=>{
const imagePath = mkData.image;
const imageRef = storage.ref().child(imagePath);
const url = await imageRef.getDownloadURL();
return {…mkData, image:url};
}))
setFutureMKData(updatedData);
} catch (error) {
console.log(‘Error:’,error);
console.log(‘futureMKData:’, futureMKData);
console.log(‘mkData:’, mkData);
}
};
fetchData();
}, [limit]);
return (
{futureMKData.map((mkData)=>(
{new Intl.DateTimeFormat(‘ru-RU’,{
day:‘numeric’,
month:‘long’,
year:‘numeric’,
hour:‘numeric’,
minute:‘numeric’,
hour12:false
}).format(mkData.time.toDate())}
{mkData.name}
Цена: {mkData.price} P.
{mkData.description.length>100
? mkData.description.substring(0,300)+‘…’
: mkData.description}
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate(‘SignUpForMK’,{mkData});}}
PastMK
import { Text, View, Image, Pressable } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import { useNavigation } from ‘@react-navigation/native’;
import {firebase} from ‘…/Firebase/firebase’;
import ‘firebase/compat/storage’;
import ‘firebase/compat/firestore’;
import React, {useState, useEffect} from ‘react’;
export default function PastMK({limit}) {
const navigation = useNavigation();
const [pastMKData, setPastMKData]=useState([]);
useEffect(()=>{
const fetchData=async()=>{
try{
let pastMKRef=firebase.firestore().collection(‘PastMK’).orderBy(‘time’,‘desc’);
if(limit){
pastMKRef=pastMKRef.limit(limit);
}
const snapshot=await pastMKRef.get();
const data = snapshot.docs.map((doc)=>({id: doc.id, … doc.data()}));
const storage=firebase.storage();
const updatedData=await Promise.all(
data.map(async (mkData)=>{
const imagePath = mkData.image;
const imageRef = storage.ref().child(imagePath);
const url = await imageRef.getDownloadURL();
return {… mkData, image:url};
}),
);
setPastMKData(updatedData);
}catch (error){
console.log(‘Error:’, error);
}
};
fetchData();
},[limit]);
return (
{pastMKData.map((mkData)=>(
<Image
source={{uri: mkData.image}}
style={gStyle.PastMKimg}
/>
{mkData.name}
{new Intl.DateTimeFormat(‘ru-RU’,{
day:‘numeric’,
month:‘long’,
year:‘numeric’
}).format(mkData.time.toDate())}
{mkData.description.length > 100
? mkData.description.substring(0, 300) + ‘…’
: mkData.description}
<Pressable style={gStyle.PastMKreadMore}
onPress={()=>navigation.navigate(‘PastMKInfo’,{mkData})}>
Читать далее
))}
its my component of result
import { Text, View, Image, Pressable } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import React from ‘react’;
export default function Result({ item }) {
return (
<View style={[gStyle.bookedMK, {flex:1}]}>
<View style={{ flexDirection: ‘column’ }}>
{item.name}
{item.description.length > 100
? item.description.substring(0, 100)+‘…’
: item.description
}
<Pressable
style={gStyle.deletebtn}
its the search screen
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity, Image } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import Header from ‘…/components/Header’;
import Footer from ‘…/components/Footer’;
import { useNavigation, useRoute } from ‘@react-navigation/native’;
import { firebase } from ‘…/Firebase/firebase’;
import ‘firebase/compat/auth’;
import ‘firebase/compat/database’;
import ‘firebase/compat/firestore’;
import React, {useState} from ‘react’;
import Result from ‘…/components/Result’;
export default function Search() {
const navigation = useNavigation();
const route = useRoute();
const results = route.params?.results || [];
{results.length > 0 ? (
results.map((item, index)=>(
))
) : (
Не найдено.
)}
This will properly render the 'Result' components for each item in the 'results' array.
With these changes, your search screen should now show the correct results when the user searches for something.
It seems that you're not fetching the image URL for each item in the 'searchResult' array. You need to do this similar to how you fetch the image URL in the 'FutureMK' and 'PastMK' components. Here's one way to do it:
Modify the 'handleSearch' function to fetch the image URL for each item in the 'searchResult' array:
const handleSearch = async () => {
if (!searchTerm.trim()) {
setSearchResult([]);
return;
}
const futureMKSnapshot = await firebase
.firestore()
.collection('FutureMK')
.where('name', '>=', searchTerm)
.where('name', '<=', searchTerm + '\uf8ff')
.get();
const pastMKSnapshot = await firebase
.firestore()
.collection('PastMK')
.where('name', '>=', searchTerm)
.where('name', '<=', searchTerm + '\uf8ff')
.get();
const futureMKData = futureMKSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}));
const pastMKData = pastMKSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}));
const results = [...futureMKData, ...pastMKData].filter(item =>
item.name.toLowerCase().includes(searchTerm.toLowerCase()));
const storage = firebase.storage();
const resultWithImages = await Promise.all(
results.map(async item => {
try {
const imagePath = item.image;
const imageRef = storage.ref().child(imagePath);
const url = await imageRef.getDownloadURL();
return { ...item, image: url };
} catch (error) {
console.log("Error fetching image URL", error);
return item;
}
})
);
setSearchResult(resultWithImages);
navigation.navigate('Search', { results: resultWithImages });
};
Modify the 'Result' component to display the image:
export default function Result({ item }) {
return (
<View style={[gStyle.bookedMK, { flex: 1 }]}>
<View style={{ flexDirection: 'column' }}>
<View style={gStyle.ProfileDetails}>
<Image
source={{ uri: item.image }}
style={gStyle.ProfileImg}
/>
<View style={gStyle.ProfileDescription}>
<Text style={gStyle.ProfileTitleOfMK}>{item.name}</Text>
<Text>
{item.description.length > 100
? item.description.substring(0, 100) + '…'
: item.description}
</Text>
</View>
</View>
</View>
<Pressable style={gStyle.deletebtn}>
<Text>Читать далее</Text>
</Pressable>
<Text style={gStyle.ProfileLine}></Text>
</View>
);
}
This should fetch and display the image correctly for each item in the 'searchResult' array.
Copy first response