Issue with React-Native Picker - managing item selection

Encountering an issue with the Picker picker component. There is an array of currencies as strings. Using the Picker to select items from this array, and have a function included in the onValueChange prop in Picker. The problem arises when trying to select an item more than once.

Initially able to select any item from the picker. However, upon attempting to choose another item, only the previously selected item is displayed in the list: multiple items For example, if EUR is chosen first and then another selection is attempted, only this appears: enter image description here

Furthermore, changing the item in the first picker also alters the selection in the second picker...for unknown reasons.

The complete code is provided below:

import React, {Component} from 'react';
import {View, Text, TextInput, Picker} from 'react-native';

class CurrencyCashScreen extends React.Component {
  state = {
    currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],
    base: 'PLN',
    amount: '',
    convertTo: 'EUR',
    result: '',
    date: '',
  };

  handleSelect = (itemValue, itemIndex) => {
    this.setState(
      {
        ...this.state,
        currencies: [itemValue],
        result: null,
      },
      this.calculate,
    );
  };

  handleInput = text => {
    this.setState(
      {
        ...this.state,
        amount: text,
        result: null,
        date: null,
      },
      this.calculate,
    );
  };

  calculate = () => {
    const amount = this.state.amount;
    if (amount === isNaN) {
      return;
    } else {
      fetch(`https://api.exchangeratesapi.io/latest?base=${this.state.base}`)
        .then(res => res.json())
        .then(data => {
          const date = data.date;
          const result = (data.rates[this.state.convertTo] * amount).toFixed(4);
          this.setState({
            ...this.state,
            result,
            date,
          });
        });
    }
  };
  
  // Remaining code sections removed for brevity

}

export default CurrencyCashScreen;

Your assistance in resolving this issue would be greatly appreciated.

Answer №1

Instead of overriding the currencies stored in state with a list containing only the selected currency in your handleSelect function, consider setting a selectedCurrency value in state and using that to populate the picker with the current value. You can update this value when calling handleSelect.

Additional Help:

Currently, you are initializing your state with the following currencies:

state = {
    currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],

However, when your handleSelect function is triggered, it changes this list in state as follows:

handleSelect = (itemValue, itemIndex) => {
    this.setState(
      {
        ...this.state,
        currencies: [itemValue], // <-- This line modifies the list of currencies
        result: null,
      },
      this.calculate,
    );
  };

As a result, after this update, your list of currencies contains only the currency you selected.

This leads to all other options disappearing upon re-render because now the currencies array in the state only has the selected currency.

To address this issue, consider having separate handle functions for each picker:

handleSelectBase = base => this.setState({ base }, this.calculate)
handleSelectConvertTo = convertTo => this.setState({ convertTo }, this.calculate)

Update your pickers to use the appropriate handler function, which should help resolve the problem.

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

What is the step-by-step process for executing the following functions: 1. magnify -> 2. spin 360 degrees -> 3. restore to original size before magnification -> 4. switch colors on and

Can you show me a demo featuring the following functions in order: 1. enlarge -> 2. rotate 360 degrees -> 3. resize to original size -> 4. change color (toggle) $(document).ready(function() { $('.tlist td div').click(function() { ...

What is the best way to establish a connection between a client and MongoDB

My attempt to connect my client with MongoDB resulted in an error message: MongoParseError: option useunifedtopology is not supported. I am unsure of the reason behind this issue and would greatly appreciate your assistance. Below is the snippet of code ...

Having trouble retrieving PHP variable values using JavaScript?

<div id="div01">01</div> <div id="div02">02</div> <img src="../img/logo.png" onclick="blueSky()"/> js function blueSky() { $.ajax({ type:'GET', url: 'test.php', success: function(respond) { document.ge ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

What is the reason that the index is consistently the final index when utilizing it to pass to a function while iterating over an array with map()?

Currently, I am utilizing the map function to iterate over an array object fetched from the server. Each object within the array is used to populate a row in a table for displaying data. I need to perform a specific action for each row by invoking a functi ...

Use Node.js to transform every spreadsheet into Json format

I have been attempting to convert an Excel file into JSON format. I tried utilizing the "xls-to-json" npm package with the following code: node_xj = require("xls-to-json"); node_xj({ input: "Auto.xlsx", // input xls output: "output.json", // output ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Store the output of a mysql query in a variable for future reference

As I work on developing a backend API for a private message system, I have encountered a challenge with one of my functions. The issue arises when I attempt to store the result of an asynchronous call in a variable for future use. Here is the code snippet ...

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

When scrolling on an IOS mobile device, the .on(click) event is triggered for fixed position elements

Whenever I click on an li element or menu, a function is triggered that moves the nav container to the left by the width of the window. However, on my iPhone, after I click to slide the container off the screen, the event gets triggered repeatedly every ti ...

Are there distinctions between using app.use("/", express.static) versus app.use(express.static)?

Is there a distinction between the following scenarios, assuming we have already executed app.set('thePath', thePath)? app.use('/', express.static(thePath)) app.use(express.static(thePath)) app.use(express.static(app.get('thePath ...

ReactJS - What makes ReactJS unique compared to other technologies?

Hey there! I'm currently trying to figure out why this specific code snippet was successful while my previous one wasn't. I've included both snippets below: SUCCESSFUL CODE: handleInputChange = (e) => { let { value } = e.target; ...

What is the best way to incorporate my CSS file into an HTML file when using Express?

When I try to host my html file using Express, it seems that my CSS is not getting applied. Why is this happening and what is the best way to include my CSS file with Express? const express = require('express'); const bodyParser = require('b ...

Link the source data within a v-for loop to the props value

I have brought in several JSON files containing different sets of data. For my parent.vue input, I aim to iterate through these JSON files dynamically. <div v-for="(item, index) in <!-- JSONFile + Rank -->" :key="index"> T ...

No options displayed in AngularJS select2 dropdown

I have implemented select2 in my code following the instructions provided at https://github.com/angular-ui/ui-select2 <div ng-controller="sampleController> <select ui-select2 ng-model="select2" data-placeholder="Pick a number"> < ...

Tips for sharing a global variable across numerous functions in various files

<script> var words = new Array(); words[1] = 'fresh'; words[2] = 'ancient'; </script> <script src="scripts/validation.js" type="text/javascript"></script> Additionally, in the validation.js file, we find: fu ...

Aborting HTTP POST requests in IE due to error code 0x2ee2

Currently, I am utilizing angularjs for file uploads to my API. The page features a multi-file select option where users can choose one or multiple files. Upon selection, the page initiates calls to the api and uploads each file individually using requests ...

What is the best way to create shared scope and transmit data within an Angular directive?

In my angular directive, I have the following code: app.directive('myDir', function () { return { restrict: 'E', scope: true, template:'<div>{{myindex}}</div>', link: function(scope, element, att ...

Issue with Angular binding not updating after being assigned in promise.then() function

Within my angular application, I have a $scope variable labeled as user which contains a name property. Whenever I click on a link to set this user variable to "test": <a href="#" ng-click="setUser()">Set User</a> Using the following functio ...

Avoiding special characters in URLs

Is there a way to properly escape the & (ampersand) in a URL using jQuery? I have attempted the following methods: .replace("/&/g", "&amp;") .replace("/&/g", "%26") .replace("/&/g", "\&") Unfortunately, none of these are y ...