Showing a loading screen based on the current state

I am trying to implement a loading screen component for Firebase data operations like user registration or login. I have defined the necessary indicators using useState, but the loading screen does not appear when the operation is in progress.
Here is my registration screen:



export function Register({ navigation }: any) {
  const [showModal, setShowModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (isLoading) return <Loading />;
  }, [isLoading]);

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <>
        <Modal
          visible={showModal}
          text={i18n.t('registerModal.title')}
          state="success"
          description={i18n.t('registerModal.description')}
          buttonText={i18n.t('registerModal.goToLogin')}
          navigation={undefined}
          setShowModal={setShowModal}
          onPress={() => {
            navigation.navigate('SignIn');
            setShowModal(false);
          }}
        />
        <Container>
          <ArrowContainer>
            <ArrowTouchable onPress={() => navigation.goBack(null)}>
              <ArrowBack width={24} height={24} />
            </ArrowTouchable>
          </ArrowContainer>

          <TitleContainer>
            <Title>{i18n.t('signup.title')}</Title>
          </TitleContainer>

          <Form setShowModal={setShowModal} setIsLoading={setIsLoading} />

          <TextContainer>
            <Text>{i18n.t('signup.alreadyHaveAccount')}</Text>
            <TouchableText onPress={() => navigation.navigate('SignIn')}>
              <SignUpText>{i18n.t('signup.singIn')}</SignUpText>
            </TouchableText>
          </TextContainer>
        </Container>
      </>
    </TouchableWithoutFeedback>
  );
}

This is my form that handles the loading state:


export function Form({ setShowModal, setIsLoading }: any) {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  async function handleUserRegister(data: FormData) {
    setIsLoading(true);

    const incomingData = await registerWithEmailAndPassword(data);

    if (incomingData) {
      setIsLoading(false);
      setShowModal(true);
    }

    setIsLoading(false);
  }

  useEffect(() => {
    ToastShowManagement(i18n.t('signup.error'), errors);
  }, [errors]);

  return (
    <Container>
      <ControlledInput
        name="username"
        control={control}
        icon="at-sign"
        placeholder={i18n.t('signup.username')}
        error={errors.username}
      />
      <ControlledInput
        name="name"
        control={control}
        icon="user"
        placeholder={i18n.t('signup.name')}
        error={errors.name}
      />
      <ControlledInput
        control={control}
        name="email"
        icon="mail"
        placeholder={i18n.t('signup.email')}
        keyboardType="email-address"
        autoCapitalize="none"
        error={errors.email}
      />
      <ControlledInput
        control={control}
        name="password"
        icon="lock"
        placeholder={i18n.t('signup.password')}
        secureTextEntry
        error={errors.password}
      />
      <ControlledInput
        control={control}
        name="passwordConfirmation"
        icon="lock"
        placeholder={i18n.t('signup.confirmPassword')}
        secureTextEntry
        error={errors.passwordConfirmation}
      />
      <PrimaryButton
        text={i18n.t('signup.button')}
        onPress={handleSubmit(handleUserRegister as any)}
        style={{ marginTop: 24 }}
      />
    </Container>
  );
}

Answer №1

The way in which useEffect is being used is incorrect

  useEffect(() => {
    if (isLoading) return <Loading />;
  }, [isLoading]);

This does not return the element to the main thread, the app.js.

To fix this, you should remove the useEffect hook

export function Register({ navigation }: any) {
  const [showModal, setShowModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  if (isLoading) return <Loading />;

  return <>{/*...*/}</>;
}

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

Properly Sequencing Ajax Calls in JavaScript

Hey there, I'm encountering a problem and struggling to find a solution. I am attempting to chain two REST call functions together and then use another function that relies on the objects returned from both calls. However, something seems to be not wo ...

Testing a Jest function that returns another function containing window.location.href

Trying to create a test case for the following function: The expected behavior is that if a successPath is provided, then onSignInSuccess should redirect to it. export const onSignInSuccess = ( data ) => { return ( ) => { global.location.href = da ...

Tips for creating a navigation bar item that displays a component depending on its active state

Trying to enhance the modularity of my code but facing difficulties. I have a tab bar and I want to render a specific component based on the clicked nav/tab item. Struggling with passing props properly, as the current code only recognizes the children valu ...

The operand n used in this context is not valid

I tried implementing the example from the Backbone manual, but it doesn't seem to be working as expected. var View = Backbone.View.extend({ tagName: 'li' }); var ex_view = new View(); console.log(ex_view.el); This code snippet throws ...

onkeypress() method not triggering the function

I have a task to prevent users from typing "%" in a textArea, so I implemented the following: However, even after clicking inside the text area, I can still type '%', indicating that my onkeypress function is not working properly or there is an ...

If the checkbox is selected, retrieve the product name and price and store them in an array

If the checkbox is checked, I want to retrieve the service name and its price in an array. To get the values of the selected items (i.e. service name and its price in an array), please explain how I can achieve this. $(document).on('click', &apos ...

What is the best way to halt all active Ajax requests initiated by a DataTables instance?

Description of Issue Every time I reset the test server to a known state, my tests fail due to ongoing Ajax requests initiated by DataTables instances. I am seeking a solution to prevent these failures by stopping the DataTables requests before resetting ...

Count the number of Mongoose Group instances within 15-second intervals

In my Model, there is a createdAt object and I want to retrieve the count of documents grouped by 15-second intervals. How can I achieve the same result as SELECT COUNT(*) FROM table WHERE time_stamp >= foo GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 15;, ...

The http.listen() function allows for the reception of terminal commands while in operation

Snippet in my code: var server = http.createServer(handleRequest); server.listen(3000, function(err){ console.log(err || 'Server listening on 3000'); }); Whenever I run the script in the terminal: nodejs file.js The script keeps running e ...

Unlock the power of responsive font sizes in React Native with NativeWind! Learn how to effortlessly make

Looking to adjust text size to fit in one line using nativewind based on screen height and width. Here is the code snippet: <Text className="text-base md:text-xl">Agree to our Terms and Privacy Policy </Text> I attempted to customiz ...

What is the reason behind the def.reject code in setTimeout not executing when the sendToSocket operation is successful?

What causes the setTimeout function inside the send method to not run if the sendToSocket operation is successful? this.send = function(type, body) { var def = Promise.defer(); try{ sendToSocket({...}); setTimeout(function() { // ...

The file could not be loaded as a result of Multipart: The boundary was not detected

Having trouble uploading images from my desktop due to a multipart boundary error. How can I set a proper boundary for image uploading? Any advice would be greatly appreciated as this is my first time attempting image uploads. Implementing an HTML event l ...

The React rendering process failed when attempting to utilize a stateless component

Struggling to integrate a stateless component with fetch in my project. The fetch API is successfully retrieving data, but for some reason, the stateless component remains blank. import React, { PropTypes } from 'react'; import { Card, CardTitle ...

Using Promises for Angular9 Modals

Looking for guidance on creating a modal in Angular 9 that utilizes a Promise for the result. Struggling to separate the promise logic from the declaration itself. <a class="button-primary" (click)="yes()">Yes</a> <a class="button-default" ...

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

Creating a bouncy 3D sphere with THREE.js

Hello everyone, I am just getting started with THREE.js and have a few questions... I'm wondering if anyone can assist me with implementing a feature where the ball gets squished when it contacts the border and changes direction? Perhaps even scaling ...

Using JavaScript to delete text and send data to the server

<script type="text/javascript"> function removeLink() { document.getElementById("tab2").deleteRow(i); } </script> </head> <body> <form action="forth.php" method="post"> <table width="600" border="1" id="tab2"> &l ...

Production environment sees req.cookies NEXTJS Middleware as undefined

Here is my latest middleware implementation: export async function middleware(request: NextRequest) { const token = request.headers.get('token') console.log(token) if (!token || token == undefined) { return NextResponse.redirect(new URL('/lo ...

What is the best way to obtain the accurate innerHeight of a div on the initial attempt

Within my webpage, there is a hidden sub navigation with its height initially set to 0. This sub navigation contains various sections of sub navs. When a section is clicked, I obtain the name of that section and then retrieve the innerHeight of the corres ...