Preventing a FOR LOOP from continuing when a matching value is found in Dropdown Validation

I'm working on implementing a validation system for my dropdown menu. If a user selects a value that has already been chosen, I want the application to display a modal for validation.

To achieve this, I have two arrays: tagsData, which contains the tags displayed in the dropdown menu, and slidesDetails, a parameter from another screen/page that helps me check if a tag has already been selected.

Using a combination of for loops and if-else statements, I iterate through both arrays to determine if the selected tag is already in use. If it is, a modal prompts the user for validation. If not, the app navigates to another screen and displays the tags in a Flatlist.

While console.log indicates where the matching tags are detected, the issue arises when the loop continues indefinitely, navigating to the next screen regardless of the condition.

Note: The Flatlist relies on detecting identical keys, emphasizing the importance of resolving the validation process.

const tagsData = [
  { id: '1', label: 'Store Schedule', tagValue: "Store Schedule" },
  { id: '2', label: 'Substandard Items', tagValue: "Substandard Items" },
  { id: '3', label: 'Promo Display', tagValue: "Promo Display" },
  { id: '4', label: 'Rack Display', tagValue: "Rack Display" },
  { id: '5', label: 'Chiller Display', tagValue: "Chiller Display" },
  { id: '6', label: 'Freezer', tagValue: "Freezer Display" }
];
const openCam = async () => {
  tagsData.map(async (item) => {
    slidesDetails.map(async (elements) => {
      var I_tagValue = item.tagValue;
      var E_tagValue = elements.tagValue;
      console.log("_____tagsValue_Data: ", E_tagValue);

      for (let i = 0; i < E_tagValue.length; i++) {
        console.log("_____I_tagValue: ", I_tagValue);
        if (I_tagValue !== E_tagValue) {
          console.log("_____tagItem: ", E_tagValue);
          console.log("Continue");
    
          setSlideDetails(updatedSlides);
          await AsyncStorage.setItem('tagKey', JSON.stringify(updatedSlides))
          navigation.dispatch(
          StackActions.replace("Deck_Report", {
                   *** route.params ***
                  })
               );
    
                break;
              } else {
                console.log("Match items")
               return (
                  <SafeAreaView>
                    <Modal visible={true}>
                      <SafeAreaView style={[styles.fill, styles.grey]}>
                        <Button title='Hide' onPress={hideModal} />
                      </SafeAreaView>
                    </Modal>
                  </SafeAreaView>
                )
              }
    
              break;
            }
          })
        })
      }

Console Log Output:

View Image Description

Flatlist Output:

View Image Description

Answer №1

Consider using a return statement instead of using break in this scenario.

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

Babel 7 encounters an issue with a lone plugin: "Error - Plugin/preset found duplicated."

The problematic plugin is @babel/plugin-transform-regenerator, which has a high download rate of 1.6 million per week. This is the complete content of my .babelrc file: { "presets": [], "plugins": [ "@babel/plugin-transform-regenerator" ] } Wh ...

My array magically transforms into an object once it reaches 22 elements, why is that happening? (node)

While working on a form with multiple checkboxes that have the same name and submitting it through a node/express post route, I encountered an issue. Here is the corresponding HTML code: https://pastebin.com/xeQae6GA The problem arises when trying to ret ...

Application suddenly crashes due to a severe issue: FATAL EXCEPTION: java.lang.RuntimeException, preventing the activity from starting

I recently updated my Ionic, Angular, and Capacitor application to the latest versions - Ionic 7, Angular 16, and Capacitor 5. After the update, I noticed that on Android, the app works fine when installed for the first time. However, upon restarting the a ...

When the input is altered, retrieve all input values within the div and then proceed to update the corresponding

The HTML provided is structured as follows: <div class="filters"> <div class="filter-label">6</div> <div class="filter-inputs"> <input type="number" name="i1" id="i1" value="1" min="0" step="1" /> & ...

Get a selection of items from a shuffled array in a random order

How can I use Powershell v4 to read a file containing SKUs and product names, randomize the entries, and display a random selection of SKUs and names? The file may contain up to twenty thousand entries, but I only need to show between one and fifty at a ti ...

The data retrieved from the $.ajax() request in Vue.js is not properly syncing with the table

After setting up an $.ajax() function and ensuring the data binding is correctly configured, I expected the data to append to a table on page load without any issues. However, the data is not appearing as expected. Is there something that I might be overlo ...

Unmounting the event post transitioning to a new page

In a component, I have implemented code that checks if the component is visible when scrolling. Here's what the code looks like: constructor(props) { super(props); this.handleScrollAnimation = this.handleScrollAnimation.bind(this); ...

Utilizing the Vuetify pagination feature in your project

I am in need of some guidance regarding the configuration of vuetify pagination. I have a card component that I loop through, but I also want to implement pagination around it. Any insights on where to start would be greatly appreciated? <v-pagination ...

Accessing JSON array data from MYSQL in SQL Server

My current project involves transferring data from MYSQL to SQL_Server using SSIS with approximately 200 tables. To tackle this, I developed a dynamic ETL process that simply requires the table name as input. In order to maintain fixed table meta-data, I ...

Guide on parsing a JavaScript file and converting the default export module to JSON with Node.js

What I'm trying to accomplish in my Node.js project is reading a sample.js file with ES Module syntax and extracting the default export from it. sample.js import foo from "foo"; const bar = [ { name: "Homer", }, { n ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...

What is the procedure for creating an array that contains elements taken sequentially from various arrays?

I am looking to extract specific elements from a given array: const initArray = [ { '18888': [ { unitId: 1, venueId: 18888, }, { unitId: 2, venueId: 18888, }, ], }, { &apos ...

Struggling with implementing Angular and TypeScript in this particular method

I'm dealing with a code snippet that looks like this: myMethod(data: any, layerId: string, dataSubstrings): void { someObject.on('click', function(e) { this.api.getSomething(a).subscribe((result: any) => { // ERROR CALL 1. It ...

Creating artwork: How to resize images without losing clarity

Struggling to display an image in a canvas element that needs to be a certain percentage of its parent container's width. Despite my efforts, the image seems to blur once added to the canvas, which is not the desired effect. I attempted to disable th ...

What is the best way to dynamically update form fields in a database after making a selection in a <select> component?

Currently, I have a form that displays a list of stars (stellar objects) with a <select> control and two <inputs>. I am seeking guidance on how to populate the two inputs from the database when the user changes the selection in the <select&g ...

Steps for redirecting from a URL containing location.hash to a different page

Recently, I decided to move a section of one of my webpages from dummy.com/get-started/#setup to its own page at dummy.com/setup. After making this change, I went ahead and deleted the old /get-started page on my website. Many people have bookmarks saved ...

Working with nested JSONArrays in Android

Looking at the json data snippet below: "categories": [ [ "Belgian Restaurant", "belgian" ], [ "Brasserie", "brasseries" ] ], I am trying to extract information from the second JSONArray (in thi ...

The Firebase read counts are increasing rapidly, even during times of inactivity

Explaining the issue I'm facing in detail, I recently embarked on developing my first larger project, a project management app using React. Everything was progressing smoothly until I started working on the task addition feature and updating graphs w ...

Currently trapped in a relentless cycle of inputting values into an array within a C programming for loop

Trying to improve my C programming skills, I decided to work on a bubble sort program. However, I ran into an issue where the for loop that assigns values to the array cells seems to get stuck after the condition is no longer met, failing to execute the ...