Encountering data loss while mapping for the first time in React Native using useState - any solutions?

const initialData = [
    {
      id: 1,
      name: `${accountList?.brideName} ${accountList?.brideSurname}`,
      type: 'Gelin',
      selected: false,
      tlText: accountList?.brideAccount?.accountTl,
      euroText: accountList?.brideAccount?.accountEuro,
      dollarText: accountList?.brideAccount?.accountUsd,
      accountHolderType: 'BRIDE'
    },
    {
      id: 2,
      name: `${accountList?.groomName} ${accountList?.groomSurname}`,
      type: 'Damat',
      selected: false,
      tlText: accountList?.groomAccount?.accountTl,
      euroText: accountList?.groomAccount?.accountEuro,
      dollarText: accountList?.groomAccount?.accountUsd,
      accountHolderType: 'GROOM'
    },
    {
      id: 3,
      name: 'Ortak Hesap',
      type: 'Gelin & Damat ',
      selected: false,
      tlText: accountList?.commonAccount?.accountTl,
      euroText: accountList?.commonAccount?.accountEuro,
      dollarText: accountList?.commonAccount?.accountUsd,
      accountHolderType: 'COMMON'
    },
  ]

const [Data1, setData1] = useState<Data[]>(initialData)

Storing data in a state variable like this helps in efficient data management. Here is how the data gets mapped when accessing this state variable:

<ScrollView showsVerticalScrollIndicator={false}>
            {Data.map((item, index) => {
              console.log('data5 ', accountList?.brideAccount?.accountTl);
              return (
                <View>
                  <PressableOpacity
                    onPress={() => {
                      setSelectedById(item.id);
                      console.log('data6 ', accountList?.brideAccount?.accountTl);
                    }}>
                    <View
                      style={{
                        paddingVertical: responsiveHeight(13),
                        paddingHorizontal: responsiveWidth(24),
                        borderBottomWidth: 1,
                        borderBottomColor: '#F3F3F3',
                        justifyContent: 'center',
                      }}>
                      <Text
                        style={{
                          lineHeight: 22,
                          fontFamily: Fonts.semiBoldRaleway,
                          fontSize: 14,
                          letterSpacing: 0.2,
                          color: '#000',
                        }}>
                        {item.name}
                      </Text>
                      <Text
                        style={{
                          lineHeight: 16,
                          fontFamily: Fonts.regularPetrona,
                          fontSize: 10,
                          letterSpacing: 0.3,
                          color: '#EA80AA',
                        }}>
                        {item.type}
                      </Text>
                      <Icon
                        style={{
                          position: 'absolute',
                          right: responsiveWidth(24),
                        }}
                        name={
                          item.selected
                            ? 'chevron-down : feather'
                            : 'chevron-right : feather'
                        }
                        size={20}
                        color="#061937"
                      />
                    </View>
                  </PressableOpacity>
                  {item?.selected && (
                    <View style={{ paddingHorizontal: responsiveWidth(24) }}>
                      <Text>{accountList?.brideAccount?.accountTl}</Text>
                      <CustomInput3 value={item?.name} />
                      <CustomInput3 leftImage={Images.tlBlack} value={item?.tlText} onChangeText={(value) => handleChangeTl(index, value)} />
                      <CustomInput3
                        leftImage={Images.dolarBlack}
                        value={item?.dollarText}
                        onChangeText={(value) => handleChangeDollar(index, value)}
                      />
                      <CustomInput3
                        leftImage={Images.euroBlack}
                        value={item.euroText}
                        onChangeText={(value) => handleChangeEuro(index, value)}
                      />
                      <CButton text='Kaydet' onPress={() => {
                        // console.log(item.accountHolderType)
                        onSubmit({ weddingCode: weddingC, accountTl: item.tlText, accountEuro: item.euroText, accountUsd: item.dollarText, accountHolderType: item.accountHolderType })
                      }} />
                    </View>
                  )}
                </View>
              );
            })}

One challenge faced is the initial data being undefined upon initiating the modal. Subsequent openings reveal the data. This begs the question of what can be done to view data from the start?

Logging the data initially poses no issues. It seems there may be a state-related problem at play. How can this be resolved?

Answer №1

If you wish to incorporate useEffect into your code, consider the following approach:

 useEffect(() => {
    if (infoData.length) updateData(infoData);
    else updateData([]);
  }, [infoData.length]);

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 does HttpClient in Angular 4 automatically assume that the request I am sending is in JSON format?

Currently, I am working with Angular 4's http client to communicate with a server that provides text data. To achieve this, I have implemented the following code snippet: this.http.get('assets/a.txt').map((res:Response) => res.text()).s ...

The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'. signup.component.html &l ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

Setting the selected value of a radio button in an edit form: a step-by-step

I'm currently developing an edit form using ReactiveFormModule. My goal is to display data in the edit form with various input elements such as textboxes, dropdowns, radio buttons, and checkboxes. I've been successful in setting values for textbo ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

gulp-tsc cannot locate the src directory

I am currently working on developing a .NET Core application using Angular2, but I keep encountering the following error: /wwwroot/NodeLib/gulp-tsc/src/compiler.ts' not found. I'm having trouble pinpointing what I might be missing. tsconfig.js ...

Change the name of the interface from the imported type

When working with Google Apps Script, I have implemented the Advanced Calendar Service, originally labeled as "Calendar". However, I have renamed it to "CalendarService". How can I incorporate this name change when utilizing the type definitions for Apps S ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

How can the map function be executed sequentially every second, using async functions, fetch API, and promises, without running in parallel?

I am facing an issue with my map function, as it needs to fetch data from an online API that only allows one request per second. I attempted to solve this problem by implementing the following code: const sleep = (ms: number) => { return new Promise(( ...

Creating easy nested list views in React Native using object data structures

I am working with an array of objects that contains user data like this: const userList = [ { "firstName": "John", "lastName": "Doe", "date": "19 March 2018" }, { "firstName": "Anna", ...

How to access enums dynamically using key in TypeScript

export enum MyEnum{ Option1, Option2, Option3 } string selection = 'Option1'; MyEnum[selection] results in an error: The type string cannot be assigned to the type MyEnum On the other hand: MyEnum['Option1'] works as ...

Observable subscription does not result in updating the value

One of the challenges I'm currently facing in my Angular application is the synchronization of data from a server. To keep track of when the last synchronization took place, I have implemented a function to retrieve this information: fetchLastSyncDate ...

The button fails to log any text to the developer console

Attempting to verify the functionality of my button by logging a message on the developer console. However, upon clicking the button, the text does not appear in the console. import { Component, EventEmitter, Input, Output } from '@angular/core'; ...

What is the best way to transform a string into an array?

After receiving an object from the http response, it looks something like this: {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] } The key in the object is represented as an array. Is there a method in ...

"An issue has been identified where TSLint and VSCode fail to display red underlines in

I am currently working on a single .ts file where I am experimenting with configuring tslint and tsconfig. To test the configuration, I intentionally added extra spaces and removed semicolons. Despite running the command tslint filename.ts and detecting e ...

The function does not throw a compiler error when a parameter is missing

Currently utilizing TSC Version 2.4.2 Please take note of the following interface: interface CallbackWithNameParameter { cb: (name: string) => void } This code snippet: const aCallback: CallbackWithNameParameter = { cb: () => {} }; Manages t ...

Troubleshooting CORS errors in axios requests within a Next.js application

Encountering an issue while attempting to make an axios call to my API on a different localhost. How can this be resolved? The tech stack being used includes Next.js, TypeScript, and Axios. Below is the function which - although written poorly for testing ...

Validate the data type based on the property

I have a CARD type that can be either a TEXT_CARD or an IMAGE_CARD: declare type TEXT_CARD = { type: "paragraph" | "h1" | "h2"; text: string; }; declare type IMAGE_CARD = { type: "img"; src: string; orient ...