My current project involves implementing a type of n-back functionality. I have replicated the concept with text appearing in random boxes, and the objective is to determine if the text matches the content of the previous box (or the box set X positions ago).
In my implementation, I utilize an array to compare the text in the current box (stored at index 0) with the text in the previous box (stored at index 1).
While this setup works smoothly in vanilla Javascript, I am encountering difficulties when trying to implement it in React Native.
Check out the code snippet here
import React, { useState } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
const [box, setBox] = useState(0)
const [same, setSame] = useState("")
const [boxesArr, setBoxesArr] = useState([])
const [hasStarted, setHasStarted] = useState(false)
function start() {
setHasStarted(true)
let num = Math.floor(Math.random() * (3 - 1 + 1) ) + 1;
setBox(num)
setBoxesArr((prev) => {
return [num, ...prev]
})
checkPrevious()
}
function checkPrevious() {
if (boxesArr[0] === boxesArr[1]) {
setSame("Yes")
} else {
setSame("No")
}
setTimeout(clearBox, 1000)
}
function clearBox() {
setBox(0)
setTimeout(start, 500)
}
return (
<View style={styles.container}>
<Text>Same as previous? {same}</Text>
<View style={styles.boxes}>
<View style={{
width: 100,
height: 100,
backgroundColor: "blue"
}}>
<Text style={styles.paragraph}>
{box === 1 ? "Here" : null}
</Text>
</View>
<View style={{
width: 100,
height: 100,
backgroundColor: "red"
}}>
<Text style={styles.paragraph}>
{box === 2 ? "Here" : null}
</Text>
</View>
<View style={{
width: 100,
height: 100,
backgroundColor: "orange"
}}>
<Text style={styles.paragraph}>
{box === 3 ? "Here" : null}
</Text>
</View>
</View>
<TouchableOpacity onPress={() => {hasStarted === false ? start() : null}}>
<View style={{backgroundColor: "purple", width: 100, marginTop: 10}}>
<Text style={{textAlign: "center", color: "white"}}>
Start
</Text>
</View>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
paddingLeft: 8,
paddingRight: 8,
paddingTop: 10
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
boxes: {
flexDirection: "row"
}
});
The issue seems to be related to the comparison logic within the "checkPrevious" function.