Unexpected behavior from comparison operator in React Native

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.

Answer №1

The issue at hand is with the code snippet below:

setBoxesArr((prev) => {
  return [num, ...prev]
});

This piece of code does not immediately update your boxesArr. The new value will only be reflected in the next render of your component. So, when you invoke checkPrevious(), the boxesArr still holds the old value and not the updated one. As the same state depends on your boxesArr, it would be better to eliminate the checkPrevious() function and the same state. Instead, calculate it during the rendering of your component like so:

const same = boxesArr[0] === boxesArr[1] ? "Yes" : "No";

You can refer to this example here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wr ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

Converting a function into a JSON string in JavaScript

My code contains a string that looks like this: var jsontext = 'function(prog) {return ' + path + ';}'; I need to convert this string into javascript code. Any ideas on how to accomplish this task? Sincerely, Thomas ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...

Error in HTML Sorting

I've been experimenting with some code from this fiddle: http://jsfiddle.net/kutyel/5wkvzbgt/ but when I copy it into Notepad++ and run it, it only displays: <html> Id: {{result.id}} Product: {{result.name}} Price: {{result.price | currency} ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

Creating a visually stunning image grid akin to the meticulously designed layouts found

Forgive my lack of knowledge, but I'm curious about how to create an image or text grid similar to Tumblr using HTML and CSS. I'm looking to achieve a layout like this: ...

Exploring the ID search feature in JavaScript

I'm facing an issue with implementing a search feature in my project. Here is the HTML snippet: HTML: <input type="text" id="search"> <video src="smth.mp4" id="firstvid"> <video src="smth2.m ...

Confirming user credentials for every page

I am currently working with an HTML page that includes front end PHP for server side scripting. One issue I have encountered is the configuration page, which can be accessed by disabling JavaScript in Mozilla settings. My current validation method relies ...

Adding a class to the body element in an HTML file using AngularJS

Greetings! Currently I am in the process of developing a web application using AngularJS SPA, which supports both English and Arabic languages. I am facing an issue with adding RTL and LTR properties by applying classes to the body HTML element in my app.j ...

Attempting to implement a click event in JavaScript/jQuery

I have been working on creating a "for" loop that assigns a function to each day in a calendar. This function, when clicked, should generate a card displaying lesson descriptions for the selected day. However, I am encountering an issue where all the card ...

Retrieve all documents from a Firebase User's collection

Recently, I created a Firebase cloud function where my goal is to access every user's internal collection named 'numbers' and examine each document within that collection for some comparisons. Do you have any insights on how I can achieve t ...

Press the Radio Button to automatically submit the form in ASP.Net Core

While working with ASP.Net Core, I encountered a scenario where I needed to update the page based on the radio button that a user clicks. I wanted the page to refresh automatically to display new data depending on the selected radio button. Would it be be ...

Utilize the search bar within a JavaScript function

One issue I am facing is taking an input from a search box and using that value as a parameter for another function. However, every time I click the button, the global variable resets itself when the page refreshes. In my javascript code, this is what I h ...

Steps for organizing an array based on unique requirements

My goal is to retrieve an array that consists of the first and second objects based on the "point" property of each object I have a specific condition where if it is satisfied, the positions will be swapped. Default: ENGLISH[0] ENGLISH[1] MATH[0] MATH[1] ...

Expanding the flexbox container to accommodate additional divs when they are added

I'm encountering an issue with a div not extending properly, causing two other divs to overlap. I've managed to position the divs correctly, but now I need the "100% all beef weenies" text to appear below the items. Any suggestions on how to achi ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Tips for iterating over two models using ng-repeat

I'm a newcomer to Angular and I have an issue that requires a neat solution: I have a div element called "SelectedList" that needs to display a list of active elements from another container. This container contains two tabs, Tab1 and Tab2, which are ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...