Demonix
Demonix

Reputation: 83

React Native Case Statement, If statement or Conditional Rendering Based on Value

I'm trying to create rank levels based on the users account XP which I get from firestore. So if the user has 3000XP he'll be level 3 for example.

I assume the best case for this would be to build a long if statement with all the possible values for example:

if (CurrentAccountXP == '1000') {
return 1
} else if (CurrentAccountXP == '2000') {
return 2
}

etc etc

Attempted solution based on Tarik's response

const CurrentAccountXP = userData.accountXP;

const levels = [
0, 1250, 2500, 3750, 5000, 6250, 7500, 8750, 10000, 11250, 12500, 13750,
15000, 16250, 17500, 18750, 20000, 21250, 22500, 23750, 25000, 26250, 27500,
28750, 30000, 31250, 32500, 33750, 35000, 36250, 37500, 38750, 40000, 41250,
42500, 43750, 45000, 46250, 47500, 48750, 50000, 51250, 52500, 53750, 55000,
56250, 57500, 58750, 60000, 61250, 62500, 63750, 65000, 66250, 67500, 68750,
70000, 71250, 72500, 73750, 75000,
];

let level = 0;
const experience = CurrentAccountXP;

levels.forEach((v, i) => {
if (experience >= v) {
  level = i + 1;
}
console.log(level);
});

Code that pulls in current accounts experience points

const [userData, setUserData] = useState({});
const user = auth.currentUser;

const GetUserData = async () => {
const response = firestore.collection("users").doc(user.uid);
const observer = response.onSnapshot(
  (docSnapshot) => {
    if (docSnapshot.exists) {
      setUserData(docSnapshot.data());
      //console.log("User Data Fetched: ", userData);
    }
  },
  (err) => {
    console.log(`Encountered error: ${err}`);
  }
);
const unsub = firestore.collection("users").onSnapshot(() => {});
  return () => unsub;
};

useEffect(() => {
  GetUserData();
}, []);

Upvotes: 0

Views: 86

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

Make sure to save the XP as numbers. Then your if statemtn could be like:

if (CurrentAccountXP >= 1000 && < 2000) {
return 1
} else if (CurrentAccountXP >= 2000 && < 3000) {
return 2
}

That way you capture also the XP if they are in between. If you create an array of levels and the min and max XPs you could generalize it with "smarter" function that loops trough the levels and checks the XP to get the correct level.

Upvotes: 1

Related Questions