ReactJS: Make select with result from two query - javascript

I'm trying to create a select in which I take datafrom two api, I compare these data and show the results in the select.
my select is a Paginate Select so I need to search if there are other data when i call API
const SelectAsyncPaginate = props => {
const [realmScelto, setRealmScelto] = useState(null);
const [listaRealm, setListaRealm] = useState([]);
useEffect(() => {
setRealmScelto(props.realmScelto);
}, [props.realmScelto]);
const loadOptions = async (searchQuery, loadedOptions, { page }) => {
const response = await fetch(
`${apiUrl}?page=${page}&size=20&deletedDate.specified=false${searchQuery.length > 3 ? `&appDesapplicazione.contains=${searchQuery}` : ''
}`
)
const response2 = await fetch(
`${apiUrlRealm}?page=${page}&size=20&deletedDate.specified=false`
)
const optionToShow = await response.json();
const optionToShow2 = await response2.json();
console.log("optionToShow1", optionToShow)
console.log("optionToShow2", optionToShow2)
const notPresent = optionToShow2.filter(ra => {
return !optionToShow.some(rua => rua.realm.id === ra.id && rua.user.perCod === props.persona.perCod.perCod);
});
setListaRealm(previousListRealm => [...previousListRealm, ...notPresent]);
console.log("listaRealm", listaRealm)
return {
options: listaRealm,
hasMore: listaRealm.length >= 1,
additional: {
page: searchQuery ? 2 : page + 1,
},
};
};
const onChange = option => {
if (typeof props.onChange === 'function') {
props.onChange(option);
}
};
return (
<AsyncPaginate
value={props.value}
loadOptions={loadOptions}
getOptionValue={option => option.realm.id}
getOptionLabel={option => option.realm.realmId}
onChange={onChange}
isSearchable={true}
placeholder="Seleziona Realm"
additional={{
page: 0,
}}
/>
);
};
If I use only one api call it works, the problem is when I call the second API because I have a loop of api calls and it not controll if there is another page and it never update the listaRealm
How can I do in your opinion??
What I would to obtain is like:
API call (apiUrl)
1.1 Check if there is another page
API call (apiUrlRealm)
2.2 Check if there is another page
Compare the two results to obtain result

Related

How to fix pagination first page load all data but onclick rest button load correctly in react

First part of my code:
const Inventory = () => {
const [products, setProducts] = useState([]);
const [pageCount,setPageCount] = useState(0);
//console.log(pageCount);
const [page,setPage] = useState(0);
const navigate = useNavigate();
useEffect(() => {
fetch(`http://localhost:3000/products?page=${page}`)
.then((res) => res.json())
.then((data) => setProducts(data));
}, [products,page]);
useEffect(()=>{
axios.get('http://localhost:3000/product-count')
.then((res) => {
const productCount = res?.data?.count;
//console.log("count product",count);
const pages = Math.ceil(productCount/6);
setPageCount(pages);
})
},[page])
Return section, this code will return pagination:
<div className="pagination">
{
[...Array(pageCount).keys()]
.map(number => <button key={number} className={page===number? 'selected': 'pagination'}
onClick={()=> setPage(number)}
>
{number+1}
</button>)
}
</div>
And this is the server-side code:
app.get("/products",async(req,res)=>{
const page = parseInt(req.query.page);
//console.log(page);
const q = {};
const cursor = productCollection.find(q);
let result;
if(page){
result = await cursor.skip(page * 6).limit(6).toArray();
}
else{
result = await cursor.toArray();
}
res.send(result);
})
// get product count
app.get("/product-count",async(req,res)=>{
const query = {};
const count = await productCollection.countDocuments(query);
res.json({count});
})
I want to load 6 data on the first load. But when data loads it displays all data. When I click the pagination button it works fine except the 1st button.
During the first load your front-end is sending page=0 to your backend.
In your server-side code you've the following statement: if (page)
But page will always be false when page=0, because 0 is a falsy value in javascript. So your statement always return the else block.
You need to change the statement to:
if (page !== undefined)

How can I stop React page to re-render?

I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working
const [load, setLoad] = useState(false);
if (load) {
return <h2>Progress</h2>;
}
const fetchPicth = async () => {
setLoad(true);
const response = await fetch(url);
const data = await response.json();
setPicth(data.pink);
};
useEffect(() => {
setLoad(false);
}, [fetchPicth]);
This can be solved using 2 approaches
Pass state in dependency array of useEffect
const [picth, setPicth] = useState([]); // Initial state
useEffect(() => {
if (picth && picth.length !== 0) { // Checks if data exists and length
//is greater than 0
setLoad(false); // Set Loading to false
}
}, [picth]);
const fetchPicth = async () => {
setLoad(true);
const response = await fetch(url);
const data = await response.json();
setPicth(data.pink);
};
Check for the length, display Progress if there is no data. Display if data is present.
{picth.length === 0 && <div>Progress</div>}
{picth.length > 0 && (
<div>
{picth.map((book, index) => {
return (
<YourComponent></YourComponent>
);
})}
Remove the fetchPicth from the dependency array. If you'd like to set load to false you can do it like this:
const [load, setLoad] = useState(false);
if (load) {
return <h2>Progress</h2>;
}
const fetchPicth = async () => {
setLoad(true);
const response = await fetch(url);
const data = await response.json();
setPicth(data.pink);
setLoad(false)
};
useEffect(() => {
fetchPicth();
}, []);
Using the code above will only fetch the data from the API only once i.e; when the component is mounted.

How to await loading data before mapping?

I'm trying to map some data that I have stored in an array (the screenshot below), but I can't seem to access it, because it is loaded asynchronously. How could I await the data? Is there a way to do it in the render function?
render() {
return (
{this.state.serials.map((number) => {
return number.s && number.s.length?
(
<h2 > {number.s[0].a}</h2>
) : null
})}
)
}
This is componentDidMount() where I get my data:
componentDidMount()
const uid = this.state.user.uid;
const gatewayRef = db.ref(uid + '/gateways');
gatewayRef.on('value', (gateways_nums) => {
const serialsArr = [];
gateways_nums.forEach((gateway_num) => {
const serialRef = db.ref('gateways/' + gateway_num.val()['gateway'])
const last_temps =[];
serialRef.on('value', (serials)=>{
const ser = []
serials.forEach((serial)=>{
ser.push(serial.val()['serial'])
})
last_temps.push({a: gateway_num.val()['gateway'], b: ser})
})
serialsArr.push({s:last_temps})
});
this.setState({serials:serialsArr})
});
}
I would really appreciate any help!

Array.map() doesn't render anything in React

I'm trying to make a list in my react app. I have retrieved data from my database, and pushed it into a list. I have doublechecked that the data shows up correctly in the console, and it does, but array.map() returns nothing. I think the problem might be that array.map() runs two times. I don't know why it runs two times.
function Dashboard() {
const user = firebase.auth().currentUser;
const [teams, setTeams] = useState([])
const history = useHistory();
useEffect(() => {
getTeams()
if (user) {
} else {
history.push("/")
}
}, [])
function Welcome() {
if (user) {
return <h1>Welcome, {user.displayName}</h1>
} else {
}
}
const getTeams = () => {
firebase.firestore().collectionGroup('members').where('user', '==', user.uid).get().then((snapshot) => {
const docList = []
snapshot.forEach((doc) => {
docList.push({
teamId: doc.data().teamId,
})
})
const teamslist = []
docList.forEach((data) => {
firebase.firestore().collection('teams').doc(data.teamId).get().then((doc) => {
teamslist.push({
name: doc.data().name,
teamId: doc.id,
})
})
})
setTeams(teamslist)
})
}
const openTeam = (data) => {
console.log(data.teamId)
}
return (
<div>
<Welcome />
<div>
<ul>
{console.log(teams)}
{teams.map((data) => {
return (
<li onClick={() => openTeam(data)} key={data.teamId}>
<h1>{data.name}</h1>
<p>{data.teamId}</p>
</li>
)
})}
</ul>
</div>
</div>
)
}
export default Dashboard
The getTeams function has a bug where it isn't waiting for the firebase.firestore().collection('teams').doc(data.teamId).get().then promises to finish before calling setTeams, so it is called with an empty array, causing React to trigger a render with the empty array.
As the promises for fetching each team resolve they will be pushed to the same array reference, but this won't trigger a rerender in React since you're not calling setTeams again when the array changes.
Try this code, which won't call setTeams until each team promise generated from docList has been resolved.
const getTeams = () => {
firebase.firestore().collectionGroup('members').where('user', '==', user.uid).get().then((snapshot) => {
const docList = []
snapshot.forEach((doc) => {
docList.push({
teamId: doc.data().teamId,
})
})
const teamslist = [];
Promise.all(docList.map((data) => {
return firebase
.firestore()
.collection('teams')
.doc(data.teamId)
.get()
.then((doc) => {
teamslist.push({
name: doc.data().name,
teamId: doc.id,
})
})
}))
.then(() => setTeams(teamslist));
})
}
A smaller edit would be to call setTeams after each separate team promise resolves, which will trigger a React render each time a new team is resolved:
.then((doc) => {
teamslist.push({
name: doc.data().name,
teamId: doc.id,
});
// create a new array, since using the same array
// reference won't cause react to rerender
setTeams([...teamslist]);
})
Many thanks to #martinstark who provided you an answer while I was unavailable.
However, there are some more things that need to be covered.
User State
In your current component, you pull the current user from Firebase Authentication, but don't handle the state changes of that user - signing in, signing out, switching user. If a user is signed in and they were to navigate directly to your dashboard, firebase.auth().currentUser could be momentarily null while it resolves the user's login state, which would incorrectly send them off to your login page.
This can be added using:
const [user, setUser] = useState(() => firebase.auth().currentUser || undefined);
const userLoading = user === undefined;
useEffect(() => firebase.auth().onAuthStateChanged(setUser), []);
Next, in your first useEffect call, you call getTeams() whether the user is signed in or not - but it should depend on the current user.
useEffect(() => {
if (userLoading) {
return; // do nothing (yet)
} else if (user === null) {
history.push("/");
return;
}
getTeams()
.catch(setError);
}, [user]);
// This getTeams() is a () => Promise<void>
const getTeams = async () => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', user.uid)
.get();
const docList = []
membersQuerySnapshot.forEach((doc) => {
docList.push({
teamId: doc.get("teamId"), // better perfomance than `doc.data().teamId`
});
});
const teamDataList = [];
await Promise.all(docList.map((data) => {
return firebase.firestore()
.collection('teams')
.doc(data.teamId)
.get()
.then(doc => teamDataList.push({
name: doc.get("name"),
teamId: doc.id
}));
}));
setTeams(teamDataList);
}
Optimizing getTeams() - Network Calls
The getTeams function in your question calls setTeams with the array [], which will be empty at the time of calling it as covered in #martinstark's answer. The "get team data" operations are asyncronous and you aren't waiting for them to resolve before updating your state and triggering a new render. While you are pushing data to them after the component has rendered, modifying the array won't trigger a new render.
While you could fetch the data for each team using db.collection("teams").doc(teamId).get(), each of these is requests is a network call, and you can only make a limited number of these in parallel. So instead of fetching 1 team per network call, you could fetch up to 10 teams per network call instead using the in operator and FieldPath.documentId().
Assuming the collectionGroup("members") targets the collections of documents at /teams/{aTeamId}/members which contain (at least):
"/teams/{aTeamId}/members/{memberUserId}": {
teamId: aTeamId,
user: memberUserId, // if storing an ID here, call it "uid" or "userId" instead
/* ... */
}
// this utility function lives outside of your component near the top/bottom of the file
function chunkArr(arr, n) {
if (n <= 0) throw new Error("n must be greater than 0");
return Array
.from({length: Math.ceil(arr.length/n)})
.map((_, i) => arr.slice(n*i, n*(i+1)))
}
// This getTeams() is a () => Promise<void>
const getTeams = async () => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', user.uid)
.get();
const teamIDList = []
membersQuerySnapshot.forEach((doc) => {
teamIDList.push(doc.get("teamId")); // better perfomance than `doc.data().teamId`
})
const chunkedTeamIDList = chunkArr(teamIDList, 10) // split into batches of 10
const teamsColRef = firebase.firestore().collection('teams');
const documentId = firebase.firestore.FieldPath.documentId(); // used with where() to target the document's ID
const foundTeamDocList = await Promise
.all(chunkedTeamIDList.map((chunkOfTeamIDs) => {
// fetch each batch of IDs
return teamsColRef
.where(documentId, 'in', chunkOfTeamIDs)
.get();
}))
.then((arrayOfQuerySnapshots) => {
// flatten results into a single array
const allDocsList = [];
arrayOfQuerySnapshots.forEach(qs => allDocsList.push(...qs.docs));
return allDocsList;
});
const teamDataList = foundTeamDocList
.map((doc) => ({ name: doc.get("name"), teamId: doc.id }));
// sort by name, then by ID
teamDataList.sort((aTeam, bTeam) =>
aTeam.name.localeCompare(bTeam.name) || aTeam.teamId.localeCompare(bTeam.teamId)
)
// update state & trigger render
setTeams(teamDataList);
}
You can also make use of this utility function to simplify & optimize the code a bit. Which gives:
// This getTeams() is a () => Promise<void>
const getTeams = async () => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', user.uid)
.get();
const teamIDList = []
membersQuerySnapshot.forEach((doc) => {
teamIDList.push(doc.get("teamId")); // better perfomance than `doc.data().teamId`
})
const teamsColRef = firebase.firestore().collection('teams');
const teamDataList = [];
await fetchDocumentsWithId(
teamsColRef,
teamIDList,
(doc) => teamDataList.push({ name: doc.get("name"), teamId: doc.id })
);
// sort by name, then by ID
teamDataList.sort((aTeam, bTeam) =>
aTeam.name.localeCompare(bTeam.name) || aTeam.teamId.localeCompare(bTeam.teamId)
)
// update state & trigger render
setTeams(teamDataList);
}
Optimizing getTeams() - Function Definition
As part of the last optimization, you could pull it out of your component or place it in its own file so that it's not redefined with every render:
// define at top/bottom of the file outside your component
// This getTeams() is a (userId: string) => Promise<{ name: string, teamId: string}[]>
async function getTeams(userId) => {
const membersQuerySnapshot = await firebase.firestore()
.collectionGroup('members')
.where('user', '==', userId)
.get();
const teamIDList = []
membersQuerySnapshot.forEach((doc) => {
teamIDList.push(doc.get("teamId")); // better perfomance than `doc.data().teamId`
})
const teamsColRef = firebase.firestore().collection('teams');
const teamDataList = [];
await fetchDocumentsWithId(
teamsColRef,
teamIDList,
(doc) => teamDataList.push({ name: doc.get("name"), teamId: doc.id })
);
// sort by name, then by ID
teamDataList.sort((aTeam, bTeam) =>
aTeam.name.localeCompare(bTeam.name) || aTeam.teamId.localeCompare(bTeam.teamId)
)
// return the sorted teams
return teamDataList
}
and update how you use it:
useEffect(() => {
if (userLoading) {
return; // do nothing
} else if (user === null) {
history.push("/");
return;
}
getTeams(user.uid)
.then(setTeams)
.catch(setError);
}, [user]);

React-native-gifted-chat with cloud firestore pagination

I'm using Firestore to store messages. In order to optimize the mobile application performances, I would like to set a limit(50) in the firestore query.
It works well and implemented the onLoadEarlier React-native-gifted-chat available in the props.
All is working fine.
But, when I send a new message in the chat, after scrolled up to see the earliers messages, only the 50 last messages with the new one, off course, are available.
So, each time I'm adding a message in the Firestore database, the onSnapshot (in the useeffect) is executed and apply the limit query.
Is there a way to avoid this ?
Thanks.
Here my useEffect :
useEffect(() => {
const messagesListener = firestore()
.collection('groups')
.doc(group._id)
.collection('messages')
.orderBy('createdAt', 'desc')
.limit(50)
.onSnapshot(querySnapshot => {
const newMessages = querySnapshot.docs.map(doc => {
const firebaseData = doc.data();
const data = {
_id: doc.id,
text: '',
createdAt: new Date().getTime(),
...firebaseData
};
return data;
});
setMessages(previousMessages => {
return GiftedChat.append(previousMessages, newMessages);
});
});
return () => messagesListener();
}, []);
I am using FlatList in react-native to render chats and I had to paginate the chats list. Since Firestore query cursor is not supported in live listener, I created two list, recentChats & oldChats.
I populate recentChats using live listener query.onSnapshot & oldChats using cursor startAfter. FlatList data is combination of both list and I take care of merging logic.
const MESSAGE_LIMIT = 15;
const ChatWindow = props => {
const { sessionId, postMessage, onSendTemplateButtonPress } = props;
// Firestore cursor is not supported in query.onSnapshot so maintaining two chat list
// oldChats -> chat list via cursor, recentChats -> chat list via live listener
const [oldChats, setOldChats] = useState([]);
const [recentChats, setRecentChats] = useState([]);
// if true, show a loader at the top of chat list
const [moreChatsAvailable, setMoreChatsAvailable] = useState(true);
const [inputMessage, setInputMessage] = useState('');
useEffect(() => {
const query = getGuestChatMessagesQuery(sessionId)
.limit(MESSAGE_LIMIT);
const listener = query.onSnapshot(querySnapshot => {
let chats = [];
querySnapshot.forEach(snapshot => {
chats.push(snapshot.data());
});
// merge recentChats & chats
if (recentChats.length > 0) {
const newRecentChats = [];
for (let i = 0; i < chats.length; i++) {
if (chats[i].sessionId === recentChats[0].sessionId) {
break;
}
newRecentChats.push(chats[i]);
}
setRecentChats([...newRecentChats, ...recentChats]);
} else {
setRecentChats(chats);
if (chats.length < MESSAGE_LIMIT) {
setMoreChatsAvailable(false);
}
}
});
return () => {
// unsubscribe listener
listener();
};
}, []);
const onMessageInputChange = text => {
setInputMessage(text);
};
const onMessageSubmit = () => {
postMessage(inputMessage);
setInputMessage('');
};
const renderFlatListItem = ({ item }) => {
return (<ChatBubble chat={item} />);
};
const onChatListEndReached = () => {
if (!moreChatsAvailable) {
return;
}
let startAfterTime;
if (oldChats.length > 0) {
startAfterTime = oldChats[oldChats.length - 1].time;
} else if (recentChats.length > 0) {
startAfterTime = recentChats[recentChats.length - 1].time;
} else {
setMoreChatsAvailable(false);
return;
}
// query data using cursor
getGuestChatMessagesQuery(sessionId)
.startAfter(startAfterTime)
.limit(MESSAGE_LIMIT)
.get()
.then(querySnapshot => {
let chats = [];
querySnapshot.forEach(snapshot => {
chats.push(snapshot.data());
});
if (chats.length === 0) {
setMoreChatsAvailable(false);
} else {
setOldChats([...oldChats, ...chats]);
}
});
};
return (
<View style={[GenericStyles.fill, GenericStyles.p16]}>
<FlatList
inverted
data={[...recentChats, ...oldChats]}
renderItem={renderFlatListItem}
keyExtractor={item => item.messageId}
onEndReached={onChatListEndReached}
onEndReachedThreshold={0.2}
ListFooterComponent={moreChatsAvailable ? <ActivityIndicator /> : null}
/>
{
Singleton.isStaff ?
null:
<ChatInput
onMessageInputChange={onMessageInputChange}
onMessageSubmit={onMessageSubmit}
inputMessage={inputMessage}
style={GenericStyles.selfEnd}
onSendTemplateButtonPress={onSendTemplateButtonPress}
/>
}
</View>
);
};
Your query is OK for the first time, for consequent queries you must use the ::startAt or ::startAfter methods.
You can find more information in the official documentation.
https://firebase.google.com/docs/firestore/query-data/query-cursors

Categories

Resources