Display a loading spinner while refreshing a list

Currently, I am in the process of developing an app using React Native. My goal is to display information (text) below my CalendarList based on data stored in an array. One of the properties in the array is the date. To achieve this, I have created a filtering function that filters the dates according to the current month. The currentMonth is updated every time there is a change in the month, as shown below:

  onMonthChange={ async (month) => {
    setIsLoading(true)
    const monthInt = parseInt(month.dateString.split("-")[1])
    await setCurrentMonth(monthInt - 1)
  }}

The filtered data looks like this:

  const filteredData = async () => {
    const temp = datas.filter((item) => {
      const dateParts = item.dayOffDate.split("-")
      const month = Number(dateParts[1]) - 1
      return month === currentMonth
    })
    setFilteredData(temp)
    await setIsLoading(false)
  }

This is how my View appears:

  <CalendarList/>
  {isLoading ? ( <ActivityIndicator size="small" />
  ) : (
    // This view displays the filtered data
    <FlatList
      data={filteredData}
      renderItem={renderListItem}
    />
  )}

My objective is to have the loading indicator appear each time the filtered data is being updated, but unfortunately, it's not functioning properly...

I would greatly appreciate any assistance or questions for clarification. Thank you :)

Answer №1

It seems that the loading indicator is not functioning correctly in the provided code due to the filteredData function not being triggered when the month changes. To resolve this issue, make sure to call the filteredData function within the onMonthChange handler and ensure it runs asynchronously.

The updated onMonthChange function should look like this:

onMonthChange={ async (month) => {
  setIsLoading(true)
  const monthInt = parseInt(month.dateString.split("-")[1])
  await setCurrentMonth(monthInt - 1)
  await filteredData() // Ensure the filteredData function is called here
}}

Update the filteredData function as follows:

const filteredData = () => {
  const temp = datas.filter((item) => {
    const dateParts = item.dayOffDate.split("-")
    const month = Number(dateParts[1]) - 1
    return month === currentMonth
  })
  setFilteredData(temp)
  setIsLoading(false)
}

Now, when the month changes, setIsLoading(true) will be triggered first, followed by the update of currentMonth and then calling the filteredData function to update the filteredData state. Once that process is complete, setIsLoading(false) will be executed, removing the loading indicator.

Ensure that the initial value of isLoading is set to false. Also, remember that await is not required when calling a setState function.

Another potential issue could be the separation of rendering <CalendarList/> and isLoading. Update the component structure like this:

<>
  {isLoading ? (
    <ActivityIndicator size="small" />
  ) : (
    // This section displays the filtered data
    <CalendarList/>
    <FlatList
      data={filteredData}
      renderItem={renderListItem}
    />
  )}
</>

Answer №2

Utilize useEffect to monitor changes in the month and filteredData.

Here is an example implementation:

const onMonthChange = month => {
  const monthInt = parseInt(month.dateString.split("-")[1])
  setCurrentMonth(monthInt - 1)
}}

const filteredData = () => {
  const temp = datas.filter((item) => {
    const dateParts = item.dayOffDate.split("-")
    const month = Number(dateParts[1]) - 1
    return month === currentMonth
  })
  setFilteredData(temp)
}

useEffect( _ => setIsLoading( true ), [ currentMonth ] )

useEffect( _ => setIsLoading( false ), [ filteredData ] )

return <>
  <ActivityIndicator size="small" animating={isLoading}/>
  <CalendarList onMonthChange={onMonthChange}/>
  <FlatList data={filteredData}/>
</>

It's worth noting that async/await should not be used 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

The specified component does not contain a property named n according to the modal error

I am new to Angular and currently working on showing a modal when clicking a marker. Despite successful compilation, I am still encountering errors at times. Could it be due to jQuery setup issues? This code is located within the HomeComponent component. ...

Modify the name of the variable when sending the object to an HTTP service in Angular version 6

export class ShopModel { public id: number; public name: string; public email: string; public phone: string; public website: string; public address: string; public gst_number: string; public pan_number: string; public ta ...

Having trouble with NextJS TypeScript and the randomUUID?() function? If you're seeing the error TS2386 that says "Overload signatures must all be

In my project setup, I have a mono-repo structure utilizing Lerna for managing 2 NextJS projects and 1 shared project. I recently attempted to integrate typescript. The NextJS projects seem to be functioning correctly (following the documentation), but I ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

The specified data type is not compatible with the current context and cannot be treated as an array

Just starting out with TypeScript and I've encountered an issue that's preventing me from successfully building my app. Everything runs smoothly on my local environment, but as soon as I try to build it, an error pops up. Here's a snippet o ...

Difficulty encountered when utilizing stockfish.js in conjunction with TypeScript

After executing npm install stockfish, I created a simple file named getBestMove.ts which contains the following code: import stockfish from 'stockfish'; const fen = '3r1r1k/pp2Nqbp/3Rb2p/2P1pp2/7P/N1P3P1/PP2QP2/R3K3 w - - 2 30' inter ...

Encountering challenges while transitioning from ngrx version 2 to version 4, specifically related to typing in array de-structuring

The error indicates a missing comma after the action parameter in the .map. Another error pops up when hovering over DataActions.AddDataAction, displaying Tuple type '[Action, AppStore]' with length '2' cannot be assigned to tuple with ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

Tips for implementing real-time filtering using React Native Realm technology

As I transition to Realm for React Native, I am eager to take advantage of their built-in queries and filtering capabilities. Currently, I have checkbox filters with three options, and the selected options are stored in an array: var filters = ['comp ...

A step-by-step guide to showcasing products of the same category in a horizontal flatlist or sectionlist using React Native

I'm trying to showcase all products with the same category in a horizontal flatlist, displaying the category name as the title. Should I group my fetched data by category, and if so, how can I achieve that? Also, which would be more suitable for this ...

Utilize ngFor in Angular Ionic to dynamically highlight rows based on specific criteria

I'm working on an application where I need to highlight rows based on a count value using ngFor in Angular. After trying different approaches, I was only able to highlight the specific row based on my count. Can someone please assist me? Check out m ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Utilizing Formik for React Native form validations

Hey there! I recently implemented formik validations in my application to handle TextInput validations. Everything is working smoothly and I can retrieve the entered values. However, I'm facing an issue with a dropdown component where I use react-nati ...

The Vue application is refusing to compile due to a syntax error caused by the presence of 'return' outside of a function

Upon attempting to run a build on my Vue app, I encountered the following syntax error. error in ./src/pages/Calendar.vue?vue&type=script&lang=ts& Syntax Error: 'return' outside of function. (175:4) 173 | getEventColor(event, Even ...

The data type 'HTMLCollection | undefined' is required to have a method called '[Symbol.iterator]()' which will then return an iterator

I'm currently working on creating a custom date-picker using web components by following a tutorial. I've encountered an error while translating the JavaScript logic to Typescript, specifically within the connectedCallback() {...} function. The e ...

What is the process for incorporating a new index signature into a class declaration from a file.d.ts in typescript?

I am facing an issue with a class in my project: // some npm module export class User { fname: string; lname: string; } Unfortunately, I cannot modify the declaration of this class from my project root since it is an npm module. I wish to add a new in ...

Having difficulty initializing a new BehaviourSubject

I'm struggling to instantiate a BehaviourSubject I have a json that needs to be mapped to this Typescript class: export class GetDataAPI { 'some-data':string; constructor (public title:string, public description:string, ...

Exploring the potential of Socket.io and Angular with the seamless integration of

I have encountered an issue regarding the use of async pipe with Observables. Initially, I assumed that returning an Observable from my service on a socket.on event would suffice. However, it appears that my approach is incorrect. Can you guide me on the c ...

What steps should I take to allow my code in an AWS Fargate container to take on an IAM role while accessing S3 using Node.js?

I've been working on implementing IAM roles to manage S3 access in my application, but I seem to be missing a crucial step. While running my code in AWS, I encountered a "missing credentials" exception, indicating that something is not configured corr ...