Define the data type of the array within hooks, then proceed with initialization

After attempting to populate the state using data fetched by RNFS.readDir, I encountered an issue where the state was being reinitialized.

interface fileUnit {
  type: string,
  index: number,
  title: string,
  path: string,
  date: string,
  size: number,
  thumbnail: string
} 
...
export const Documents = () => {
  const hookState = React.useState([])
  const documents: fileUnit[] = hookState[0]
  const setDocuments: any =hookState[1]

  React.useEffect(() => {
    RNFS.readDir(RNFS.DocumentDirectoryPath)
      .then(async (results: any[]) => {
        results.map((file, key) => {
          const fileUnit: fileUnit= { type: file.isFile()? 'file': 'folder', index: key, title: file.name, path: file.path, date: file.mtime, size: file.size, thumbnail: ''}

          setDocuments([...documents, fileUnit])

        })
      })
  }, [])
}

My expectation was to append new data to the existing state array, but it was instead initialized anew.

Therefore, I wondered if setting the state type as:

const [documents, setDocuments] = React.useState([]);

would solve this issue?

Answer №1

Have you considered trying this approach?

const MyDocs = () => {
  const stateHook = React.useState([])
  const docs: fileUnit[] = stateHook[0]
  const setDocs: any = stateHook[1]

  React.useEffect(async () => {
    const results: any[] = await RNFS.readDir(RNFS.DocumentDirectoryPath)
    const updatedFiles: fileUnit = results.map((file, key) => {
        return { type: file.isFile()? 'file': 'folder', index: key, title: file.name, path: file.path, date: file.mtime, size: file.size, thumbnail: ''}
    })
    setDocs([...docs, updatedFiles])
  }, [])
}

You can also define setState variables as requested. This is a commonly used method.

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

Guide to creating a function and exporting it to a component in react with the help of typescript

I have a ParentComponent where I need to integrate a function from a separate file and incorporate it into the ParentComponent. The structure of the ParentComponent is as follows: function ParentComponent() { const count = 5; // this value usually co ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

Troubleshooting: React Native and OneSignal notifications not showing up

Currently, I am developing an app in React Native and working on integrating notifications with OneSignal. Although I am able to efficiently receive notifications, I do not want them to be displayed on the screen when they are received. I came across a ` ...

Different types of arrays suitable for the useState hook

I have a scenario where I am utilizing setState to assign an array of objects. Here is the code snippet: const [friendList, setFriendList] = useState<any>(); const _onCompleted = (data: any) => { let DATA = data.me.friends.map( (item ...

mobx: invoking a class method upon data alteration

Is it possible to utilize the Mobx library in order to trigger a class method whenever data changes? For instance, when MyObject assigns a value of 10 to container['item'], can we have the myaction method invoked? class MyElement extends Compone ...

What is the process for performing interpolation in Angular version 8?

In my Angular project, I have 2 components working together. Component A sends an id using the following code snippet: <a [routerLink]="['/numbersbyareacode', element.id]"> {{element.title}} </a> Upon navigating to Component B, ...

Following an update from typescript version 2.3.4 to 2.4.2, I encountered a compilation error stating, "The type definition file for 'reflect-metadata' cannot be found."

Recently, I encountered an issue with my React / Mobex application written in TypeScript and built by Webpack 1. Upon updating the TypeScript version from 2.3.4 to 2.4.2, an error started occurring. The error message reads: ERROR in C:\myproject&bsol ...

Guide on obtaining the total value from a JSON Array in Angular 2 using TypeScript

I received a JSON response which includes carts values with different amounts. "carts": { "value": [ { "Amt": 40 }, { "Amt": 20.25 }, ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

Populating a class object with all fields simultaneously from a FormGroup

Working with Angularjs projects involves creating an input form with various fields to collect data. The provided documentation includes examples on how to retrieve individual field values as well as how to save all the fields at once, potentially in a cla ...

How to capture a screenshot of the current screen using Nativescript programmatically

After taking a screenshot in a NativeScript app, is there a way to display a popup asking if the user wants to save the picture? I attempted using the 'nativescript-screenshot' plugin, but it only copies elements within the application: nat ...

Can someone give me a thorough clarification on exporting and importing in NodeJS/Typescript?

I am inquiring about the functionality of exports and imports in NodeJS with TypeScript. My current setup includes: NodeJS All written in Typescript TSLint for linting Typings for type definitions I have been experimenting with exports/imports instead o ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

Adding Typescript to a Nativescript-Vue project: A step-by-step guide

Struggling over the past couple of days to configure Typescript in a basic template-generated Nativescript-Vue project has been quite the challenge. Here's my journey: Initiated the project using this command: ERROR in Entry module not found: Erro ...

How can TypeScript be used to access a state object conditionally using an array?

I have an issue with my object that has an extended state object. I created an array of values to check using a for of loop, but I am having trouble making the array value compatible with the state object's key. How can I inform TypeScript that the va ...

flickering effect problem

What could be causing the issue where [@fadeInOut] only works on the initial page load when toggling isExpanded to hide or show content? Due to [@fadeInOut], the content stops showing up. Any thoughts on what might be causing this and any alternative solut ...

Steps for building a forked React Native npm package:

I made modifications to a React Native npm library called react-native-calendars by forking it. Now I want to integrate these changes into my project. I have added it to my project using the following command: npm i git+<my_forked_git_repo_url> The ...

Upon initial loading, the default sidenav in Angular is not selected

I need to ensure that the sidenav loads the basic page during the initial load. This is controlled by the routing.ts file shown below: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; i ...

Next.js encountered an error when trying to locate the 'net' module while working with PostgreSQL

I'm facing a challenge in my Next.js project while attempting to retrieve all records from a table. The error message I'm encountering is "Module not found: Can't resolve 'net'" with an import trace pointing to multiple files withi ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...