I’m engaged on a gaming app and this appears to hassle me for a really very long time. I attempted completely different approaches however none of them appear to work. I hope somebody will assist me in fixing this most replace depth concern. That is coming once I operating a stress take a look at on the handleLikeLoadout perform.
(NOBRIDGE) ERROR Warning: Most replace depth exceeded. This could occur when a element calls setState inside useEffect, however useEffect both does not have a dependency array, or one of many dependencies modifications on each render.
What modifications do I have to make so this error will. not hassle me anymore? That is the code that I’m executing:
import React, { useState, useEffect, useMemo } from "react";
import {
View,
Textual content,
StyleSheet,
ImageBackground,
Dimensions,
Alert,
TouchableOpacity,
Share
} from "react-native";
import { TabView, TabBar } from "react-native-tab-view";
import Banner from "./Banner";
import { LinearGradient } from "expo-linear-gradient";
import Icon from "react-native-vector-icons/FontAwesome5";
import WZLoadouts from "./WZLoadouts";
import WZFavouriteLoadouts from "./WZFavouriteLoadouts";
import WZMyLoadouts from "./WZMyLoadouts";
import WZCreateLoadout from "./WZCreateLoadout";
import { getDatabase, ref, get, push, replace, set, onValue, take away } from "firebase/database";
import { getAuth } from "firebase/auth";
import fetchAllUsers from '../property/knowledge/retrieveData'
import { isEqual as deepEqual } from "lodash";
const CodComponent = () => {
const [index, setIndex] = useState(0);
const [list, setList] = useState({});
const [user, setUser] = useState({userLoad: [], userFav: [] });
const [users, setUsers] = useState({});
const [userFav, setUserFav] = useState([]); // Initialize as an array
const [isAdmin, setIsAdmin] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
const auth = useMemo(() => getAuth(), []);
const db = useMemo(() => getDatabase(), []);
const initialLayout = { width: Dimensions.get("window").width };
const backgroundImage = require("../property/pictures/v197_60.png");
const weaponAttachments = {
AK41: {
Optic: ["3x Optic", "Holo Optic", "Red Dot Sight", "Thermal Scope", "Viper Reflex Sight"],
Muzzle: ["Muzzle 1", "Muzzle 2", "Flash Hider", "Suppressor", "Compensator", "Monolithic Suppressor"],
Inventory: ["Stock 1", "Stock 2", "Collapsed Stock", "Tactical Stock", "Pro Stock"],
Barrel: ["Barrel 1", "Barrel 2", "Long Barrel", "Heavy Barrel", "Short Barrel", "Precision Barrel"],
Underbarrel: ["Vertical Grip", "Angled Grip", "Bipod", "Commander Grip"],
RearGrip: ["Rubber Grip", "Taped Grip", "Granulated Grip", "Speed Grip"],
Ammunition: ["Extended Mag", "Fast Mags", "FMJ Rounds", "High Velocity Rounds", "Drum Mag"],
Laser: ["Laser Sight", "Infrared Laser", "Tactical Laser"],
Perk: ["FMJ", "Fully Loaded", "Recon", "Sleight of Hand", "Ghost"],
},
M4A1: {
Optic: ["3x Optic", "Holo Optic", "Red Dot Sight", "Thermal Scope", "Viper Reflex Sight"],
Muzzle: ["Muzzle 1", "Muzzle 2", "Flash Hider", "Suppressor", "Compensator", "Monolithic Suppressor"],
Inventory: ["Stock 1", "Stock 2", "Collapsed Stock", "Tactical Stock", "Pro Stock"],
Barrel: ["Barrel 1", "Barrel 2", "Long Barrel", "Heavy Barrel", "Short Barrel", "Precision Barrel"],
Underbarrel: ["Vertical Grip", "Angled Grip", "Bipod", "Commander Grip"],
RearGrip: ["Rubber Grip", "Taped Grip", "Granulated Grip", "Speed Grip"],
Ammunition: ["Extended Mag", "Fast Mags", "FMJ Rounds", "High Velocity Rounds", "Drum Mag"],
Laser: ["Laser Sight", "Infrared Laser", "Tactical Laser"],
Perk: ["FMJ", "Fully Loaded", "Recon", "Sleight of Hand", "Ghost"],
},
BullFrog: {
Optic: ["3x Optic", "Holo Optic", "Red Dot Sight", "Thermal Scope", "Viper Reflex Sight"],
Muzzle: ["Muzzle 1", "Muzzle 2", "Flash Hider", "Suppressor", "Compensator", "Monolithic Suppressor"],
Inventory: ["Stock 1", "Stock 2", "Collapsed Stock", "Tactical Stock", "Pro Stock"],
Barrel: ["Barrel 1", "Barrel 2", "Long Barrel", "Heavy Barrel", "Short Barrel", "Precision Barrel"],
Underbarrel: ["Vertical Grip", "Angled Grip", "Bipod", "Commander Grip"],
RearGrip: ["Rubber Grip", "Taped Grip", "Granulated Grip", "Speed Grip"],
Ammunition: ["Extended Mag", "Fast Mags", "FMJ Rounds", "High Velocity Rounds", "Drum Mag"],
Laser: ["Laser Sight", "Infrared Laser", "Tactical Laser"],
Perk: ["FMJ", "Fully Loaded", "Recon", "Sleight of Hand", "Ghost"],
},
};
useEffect(() => {
const codRef = ref(db, "COD");
const codListener = onValue(codRef, (snapshot) => {
const loadouts = snapshot.exists() ? snapshot.val() : {};
const sortedLoadouts = Object.values(loadouts)
.type((a, b) => (b.likes?.size || 0) - (a.likes?.size || 0))
.cut back((acc, loadout) => {
acc[loadout.id] = loadout;
return acc;
}, {});
setList((prevList) => {
const prevLoadouts = Object.values(prevList);
const sortedPrevLoadouts = prevLoadouts
.type((a, b) => (b.likes?.size || 0) - (a.likes?.size || 0));
if (JSON.stringify(sortedPrevLoadouts) !== JSON.stringify(Object.values(sortedLoadouts))) {
return sortedLoadouts;
}
return prevList;
});
});
let userListener;
const consumer = auth.currentUser;
if (consumer) {
const userRef = ref(db, `customers/${consumer.uid}`);
userListener = onValue(userRef, (snapshot) => {
const userData = snapshot.exists()
? snapshot.val()
: { userFav: [], userLoad: [] };
setUser((prevUser) => {
if (!deepEqual(prevUser, userData)) {
return userData;
}
return prevUser;
});
setUserFav((prevFav) => {
if (!deepEqual(prevFav, userData.userFav)) {
return userData.userFav;
}
return prevFav;
});
});
}
return () => {
codListener();
if (userListener) userListener();
};
}, [db, auth]);
const fetchMoreLoadouts = async () => {
const codRef = ref(db, "COD");
const snapshot = await get(codRef);
const allLoadouts = snapshot.exists() ? snapshot.val() : {};
const currentLoadouts = Object.keys(listing); // IDs of loadouts already displayed
const remainingLoadouts = Object.values(allLoadouts)
.filter((loadout) => !currentLoadouts.contains(loadout.id)) // Exclude already loaded objects
.type((a, b) => (b.likes?.size || 0) - (a.likes?.size || 0)); // Kind remaining loadouts
return remainingLoadouts.slice(0, 10); // Fetch the following 10 loadouts
};
const loadMoreLoadouts = async () => {
const newLoadouts = await fetchMoreLoadouts();
setList((prevList) => {
const mergedList = { ...prevList };
// Add new loadouts and re-sort the whole listing
newLoadouts.forEach((loadout) => {
mergedList[loadout.id] = loadout;
});
return Object.values(mergedList)
.type((a, b) => (b.likes?.size || 0) - (a.likes?.size || 0)) // Re-sort by likes
.cut back((acc, loadout) => {
acc[loadout.id] = loadout;
return acc;
}, {});
});
};
const handleDeleteLoadout = (loadout) => {
Alert.alert(
"Delete Loadout",
"Are you certain you need to delete this loadout?",
[
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: async () => {
try {
const loadoutRef = ref(db, `COD/${loadout.id}`); // Reference to the loadout data
const userLoadRef = ref(db, `users/${loadout.userId}/userLoad`); // Reference to the user's loadout array
const usersRef = ref(db, "users"); // Reference to all users for additional cleanup if needed
// Fetch the user's userLoad array
const userSnapshot = await get(userLoadRef);
if (userSnapshot.exists()) {
const userLoadArray = userSnapshot.val(); // Firebase array format
const updatedUserLoad = userLoadArray.filter((id) => id !== loadout.id);
// Update the user's loadout array
await update(ref(db, `users/${loadout.userId}`), { userLoad: updatedUserLoad });
}
// Remove the loadout from the COD collection
await remove(loadoutRef);
// Clean up any additional userFav references if applicable
const usersSnapshot = await get(usersRef);
if (usersSnapshot.exists()) {
const usersData = usersSnapshot.val();
const updates = {};
// Remove the loadout from all userFav arrays
Object.entries(usersData).forEach(([userId, userData]) => {
if (userData.userFav && userData.userFav.contains(loadout.id)) {
updates[`users/${userId}/userFav`] = userData.userFav.filter(
(favId) => favId !== loadout.id
);
}
});
if (Object.keys(updates).size > 0) {
await replace(ref(db), updates); // Apply all updates directly
}
}
// Replace native state
setList((prevList) => {
const updatedList = { ...prevList };
delete updatedList[loadout.id];
return updatedList;
});
setUser((prevUser) => ({
...prevUser,
userLoad: prevUser.userLoad?.filter((id) => id !== loadout.id),
}));
Alert.alert("Success", "Loadout deleted efficiently.");
} catch (error) {
console.error("Error deleting loadout:", error);
Alert.alert("Error", "Couldn't delete loadout: " + error.message);
}
},
},
]
);
};
// Deal with sharing a loadout
const handleShareLoadout = async (loadout) => {
strive {
// Assemble the distinctive URL with the app-specific scheme and loadout ID
const loadoutUrl = `coleeApp://expo-development-client/cod`;
console.log(loadout.gun.attachments)
// Guarantee attachments is an array or use a fallback
const attachmentsList = Array.isArray(loadout.gun.attachments)
? loadout.gun.attachments.be part of(", ") // Be a part of array components as a string
: loadout.gun.attachments && typeof loadout.gun.attachments === 'object'
? Object.values(loadout.gun.attachments).be part of(", ") // Be a part of object values if attachments is an object
: "No attachments"; // Fallback when attachments is neither an array nor an object
// Share the message with detailed loadout data
const shareOptions = {
message: `Try this loadout:n` +
`Title: ${loadout.title.identify}n` +
`Vary: ${loadout.title.vary}n` +
`Kind: ${loadout.title.sort}n` +
`Recreation: ${loadout.title.recreation}nn` +
`Gun: ${loadout.gun.identify}n` +
`Attachments: ${attachmentsList}nn` +
`Open within the app: ${loadoutUrl}`,
};
await Share.share(shareOptions);
} catch (error) {
Alert.alert("Error", `Couldn't share the loadout: ${error.message}`);
}
};
const createLoadout = async (
title,
weapon,
vary,
recreation,
weaponType,
attachments,
uid
) => {
// console.log(attachments);
strive {
// Examine if the consumer is authenticated
if (!uid) {
throw new Error("Person isn't authenticated");
}
// Save to `COD` root object in Firebase
const codRef = ref(db, "COD");
const newLoadoutRef = push(codRef);
// Get the generated ID of the loadout
const loadoutId = newLoadoutRef.key;
// Put together the brand new loadout object with loadoutId
const newLoadout = {
id: loadoutId, // Add the loadoutId right here
title: { identify: title, vary, sort: weaponType, recreation },
gun: { identify: weapon, attachments },
userId: uid,
likes: [],
updatedAt: new Date().toISOString(),
};
// Save the loadout to Firebase
await replace(newLoadoutRef, newLoadout);
// Replace the consumer's `userLoad` array in Firebase
const userRef = ref(db, `customers/${uid}`);
const userSnapshot = await get(userRef); // Fetch present consumer knowledge
if (userSnapshot.exists()) {
const userData = userSnapshot.val();
const updatedUserLoad = [...(userData.userLoad || []), loadoutId];
await replace(userRef, {
userLoad: updatedUserLoad,
});
} else {
// Deal with the case the place the consumer object does not exist
await set(userRef, { userLoad: [loadoutId] });
}
// Replace the listing within the state
setList((prevList) => {
const updatedList = { ...prevList, [newLoadout.id]: newLoadout };
return Object.values(updatedList)
.type((a, b) => (b.likes?.size || 0) - (a.likes?.size || 0))
.slice(0, 10)
.cut back((acc, loadout) => {
acc[loadout.id] = loadout;
return acc;
}, {});
});
Alert.alert("Success", "Loadout efficiently created.");
// console.log("Loadout efficiently created and saved to Firebase.");
} catch (error)
};
const handleLikeLoadout = async (loadout) => {
strive {
// Examine if the consumer is authenticated
const consumer = auth.currentUser;
if (!consumer) {
Alert.alert(
"Authentication Required",
"Please log in to love or in contrast to posts. This helps us guarantee a personalised expertise for you.",
[{ text: "Cancel", style: "cancel" }],
{ cancelable: true }
);
return;
}
const userId = consumer.uid;
const currentLikes = loadout.likes || []; // Guarantee likes is an array
const isLiked = currentLikes.contains(userId);
// Toggle the like standing for the loadout
const updatedLikes = isLiked
? currentLikes.filter((uid) => uid !== userId) // Take away consumer's like
: [...currentLikes, userId]; // Add consumer's like
const loadoutRef = ref(db, `COD/${loadout.id}`);
await replace(loadoutRef, { likes: updatedLikes });
// Fetch and replace the consumer's favorites
const userRef = ref(db, `customers/${userId}`);
const userSnapshot = await get(userRef);
const userData = userSnapshot.exists()
? userSnapshot.val()
: { userFav: [] }; // Default to an object with empty userFav array
const updatedUserFav = isLiked
? (userData.userFav || []).filter((favId) => favId !== loadout.id) // Guarantee array earlier than filter
: [...(userData.userFav || []), loadout.id]; // Add loadout ID to favorites
await replace(userRef, { userFav: updatedUserFav });
// Replace the native state
setList((prevList) => ({
...prevList,
[loadout.id]: { ...prevList[loadout.id], likes: updatedLikes },
}));
setUserFav(updatedUserFav); // Replicate the up to date favourite listing within the state
} catch (error) {
console.error("Error updating like/favourite:", error);
Alert.alert(
"Error",
"An error occurred whereas processing your request. Please strive once more later."
);
}
};
useEffect(() => false);
, [user]);
const renderScene = ({ route }) => {
swap (route.key) {
case "first":
return ;
// case "second":
// return (
//
// userFav.contains(_[0].id) // Filter by favorites
// )}
// />
// );
// case "third":
// return (
//
// consumer.userLoad.contains(_[0].id)
// )}
// userFav={userFav}
// />
// );
case "fourth":
return (
);
default:
return null;
}
};
const renderLabel = ({ route }) => {
return (
{route.key === "first" && }
{route.key === "second" && }
{route.key === "third" && }
{route.key === "fourth" && }
);
};
const [routes] = useState([
{ key: "first" },
{ key: "second" },
{ key: "third" },
{ key: "fourth" },
]);
return (
(
{props.navigationState.routes.map((route, idx) => (
setIndex(idx)} // Handle tab switching
>
{renderLabel({ route })}
))}
)}
/>
);
};
const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
width: "100%",
height: "100%",
},
pageContentContainer: {
flex: 1,
padding: 10,
marginTop: 105, // Adjust this value based on banner height
},
tabContainer: {
flex: 1,
marginTop: 25,
},
scrollView: {
flex: 1,
},
tabBar: {
flexDirection: "row",
borderRadius: 10,
overflow: "hidden",
},
tabItem: {
flex: 1,
alignItems: "center",
justifyContent: "center",
paddingVertical: 10,
},
tabBarTransparent: {
backgroundColor: "transparent",
shadowColor: "transparent",
},
indicator: {
backgroundColor: "white",
},
tabLabel: {
color: "white",
fontWeight: "bold",
fontSize: 12, // Adjust font size to fit in one line
},
labelContainer: {
flexDirection: "row",
alignItems: "center",
},
});
export default CodComponent;
I tried all the solutions present in any other opened issues