Not being Redirected to AppNavigator after CognitoHostedUi Sign in

Hello Im having trouble setting up authentication with the default Cognito Hosted UI for my mobile application.
I am working with Amplify in a react-native project.

Ive got sign in with Apple and google both configured.

When I login or successfully create and verify an account instead of being redirected to the AppNavigator I remain at the welcomeScreen.js.

Accounts are successfully being created in the user pool.

I also have deep linking configured in the AppDelegate and Url in info.plist file.

here is my code:

WelcomeScreen.js

    const WelcomeScreen = () => {
  const domain = " ";
  const redirectSignIn = "Name://";
  const clientId = " ";

  const handleOpenSignIn = async () => {
    const url = `https://${domain}/oauth2/authorize?client_id=${clientId}&response_type=code&scope=email+openid+profile&redirect_uri=${encodeURIComponent(redirectSignIn)}`;

    console.log("Attempting to open URL:", url); // Logs the URL being opened

    try {
      if (await InAppBrowser.isAvailable()) {
        console.log("Opening In-App Browser for sign-in");
        const result = await InAppBrowser.openAuth(url, redirectSignIn, {});
        console.log("In-App Browser closed, result:", result);

        if (result.type === 'success' && result.url) {
          console.log("Successful authentication, URL:", result.url);
        } else {
          console.log("Authentication was not successful");
        }
      } else {
        console.error("In-app browser is not available");
      }
    } catch (error) {
      console.error("Error opening in-app browser for sign-in:", error);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome to X!</Text>
      <Text style={styles.paragraph}>
        Revolutionize the way you X.
      </Text>

      <View style={styles.buttonContainer}>
        <TouchableOpacity
          style={styles.loginButton}
          onPress={handleOpenSignIn}
        >
          <Text style={styles.buttonText}>Log In or Sign Up</Text>
        </TouchableOpacity>
       
      </View>
    </View>
  );
};

App.js:

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isAuthenticating, setIsAuthenticating] = useState(true); // New state to track if auth check is in progress

  const checkAuthState = async () => {
    try {
      await Auth.currentAuthenticatedUser();
      console.log('Auth state changing: User is authenticated'); // Log when authenticated
      setIsAuthenticated(true);
    } catch {
      console.log('Auth state changing: User is not authenticated'); // Log when not authenticated
      setIsAuthenticated(false);
    }
    setIsAuthenticating(false); // Set to false after checking auth state
  };


  useEffect(() => {
    const listener = (data) => {
      console.log('Event received:', data.payload.event);
      if (data.payload.event.includes('_failure')) {
        console.log('Error details:', data.payload.data);
      }
      switch (data.payload.event) {
        case 'signIn':
          setIsAuthenticated(true);
          setIsAuthenticating(false); // Set to false upon sign-in
          console.log('Auth state changing: User signed in');
          break;
        case 'signOut':
          setIsAuthenticated(false);
          setIsAuthenticating(false); // Set to false upon sign-out
          console.log('Auth state changing: User signed out');
          break;
        default:
          console.log(`Unhandled event: ${data.payload.event}`);
          break;
      }
    };

    Hub.listen('auth', listener);

    checkAuthState();

    return () => Hub.remove('auth', listener);
  }, []);

  // Render a loading indicator while checking authentication state
  if (isAuthenticating) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    <ThemeProvider>
      <NavigationContainer>
        {isAuthenticated ? <AppNavigator /> : <WelcomeScreen />}
      </NavigationContainer>
      <Toast />
    </ThemeProvider>
  );
}

export default App;

here are Logs when I attempt to sign in

 LOG  Auth state changing: User is not authenticated
 LOG  Attempting to open URL: https://auth-Name.auth.us-east-2.amazoncognito.com/oauth2/authorize?client_id=4sj96pmn8mukg3td835pen0nve&response_type=code&scope=email+openid+profile&redirect_uri=Name%3A%2F%2F
 LOG  Opening In-App Browser for sign-in
 LOG  Event received: parsingCallbackUrl
 LOG  Unhandled event: parsingCallbackUrl
 LOG  In-App Browser closed, result: {"type": "success", "url": "CallBackUrlName://?code=6ce42774-39e0-4838-bec1-ada64cb75039"}
 LOG  Successful authentication, URL: CallBackUrlName://?code=6ce42774-39e0-4838-bec1-ada64cb75039

Detect if reportValidity() is currently showing the validityMessage on a DOM element?

Calling reportValidity() on in invalid field causes the validation message to show in a browser-dependent way.

However, calling reportValidity() again causes the validation message to disappear on Safari but not Firefox. Repeatedly calling it causes it to toggle, making cross-browser validation difficult.

In my specific case, I want to show the validation message on form submit and on input focus. When you submit the form and it is invalid, the event triggers reportValidity() on the form. However, this will focus the input that is invalid, triggering the reportValidity() again from my focus event, hiding the message that was just shown.

Is there a way to reliably show the message when you don’t know if it’s already showing? Does the browser provide an interface for detecting if the validity message is showing?

Example:

const input = document.getElementById("invalid")
input.addEventListener("focus", () => input.reportValidity())
const form = document.getElementById("form")
form.addEventListener("submit", (e) => { e.preventDefault(); form.reportValidity() })
<form action="#" id="form">
  <input type="number" max="5" value="10" name="invalid" id="invalid" autocomplete="off">
  <input type="submit" value="validate">
</form>

On Safari, this example will cause the validation message to hide when submitting the form. This is not the desired behavior.

Tailwind Rebuild never stops

My Flask app uses Tailwind for the css. The website was working perfectly before but recently I’ve started encountering issues with tailwind. I have run a tailwind build script for my app and normally the script would update css if it detects changes in any of the target files.

However, when I run the script now, recently the tailwind just says ‘Rebuilding…’ without the ‘Done’ message. so the rebuild never stops.

(venv) danish@Danishs-MacBook-Air portfolio-website % npm run tailwind

> [email protected] tailwind
> npx tailwindcss -i ./static/src/input.css -o ./static/css/main.css --watch


Rebuilding...

How do I fix this issue?

How to check state and execute function after some delay in React?

I am trying to execute a function if the state doesn’t change which is updated due to database fetch. I mean:

const [value, setValue] = useState(false)
const func = () => {
  ...
}

setTimeout(()=>{
  if(value) {
     func()
  } else {
    Alert.alert("Nothing!")
  }
},20000)

fetchData.then(()=>setValue(true))

But this timeout method takes the initial state of the const value, and executes due to its initial value, not depending its value after 20 seconds. Even if it updates to true.

How can I achieve this object?

How to do line-by-line performance profiling?

Is there any way to do this in modern Chrome? Im not looking for ‘total function time’ and I dont want to add a console timer to every piece of code manually. Chrome use to have a line-by-line profiling view back around 2018 / 2020 but it doesnt seem to exist anymore.

pic of old Chrome js profiling

Have tried to find this feature in modern Chrome but cant. Tried to download old Chrome but it wont run even when I delete my old Chrome / Chromium profile.

Need to Extract Particular Data from PDF file

`I am trying to extract the data from a pdf file however not able to.

Below is the code that I am using`

import fitz  # PyMuPDF

def extract_data_from_pdf(pdf_path):
    # Open the PDF file
    pdf_document = fitz.open(pdf_path)

    # Create a dictionary to store extracted data
    extracted_data = {}

    # Define the fields you want to extract
    fields_to_extract = [
        "Vehicle Registration No",
        "Make",
        "Model",
        "Policy No.",
        "Vehicle Make / Model",
        "RTO City",
        "CC/KW",
        "Mfg Yr",
        "Seating Capacity",
        "Basic Third Party Liability",
        "Total Tax Payable in",
        "Total Premium Payable In",
        "RTO Location",
    ]

    # Loop through each page of the PDF
    for page_number in range(pdf_document.page_count):
        page = pdf_document[page_number]

        # Loop through each field to extract
        for field in fields_to_extract:
            # Search for the field in the page text
            search_result = page.search_for(field + ':')  # Added ':' to match the field name exactly

            # If the field is found, extract the text
            if search_result:
                field_text = page.get_text("text", clip=search_result[0])
                extracted_data[field] = field_text.replace(field + ':', '').strip()

    # Close the PDF document
    pdf_document.close()

    return extracted_data

# Specify the path to your PDF file
pdf_path = "path/to/your/pdf/file.pdf"

# Extract data from the PDF
data = extract_data_from_pdf(pdf_path)

# Print the extracted data
for key, value in data.items():
    print(f"{key}: {value}")

#It is giving below result

Vehicle Registration No: Vehicle Registration
Make: Make
Model: Model
Policy No.: Policy No.
Vehicle Make / Model: Vehicle Make / Model
RTO City: RTO City
CC/KW: CC/KW
Mfg Yr: Mfg Yr
Seating Capacity: Seating
Basic Third Party Liability: Basic Third Party Liability
Total Tax Payable in: Total Tax Payable in
Total Premium Payable In: Total Premium Payable In
RTO Location: RTO Location

#Instead of

Vehicle Registration No: PB03AW9668
Make: HONDA MOTORCYCLE
Model: ACTIVA 5G STD
Policy No.: 3005/A/326653656/00/B00
Vehicle Make / Model: HONDA MOTORCYCLE / ACTIVA 5G STD
RTO City: RTO City
CC/KW: 109
Mfg Yr: 2018
Seating Capacity: 2
Basic Third Party Liability: 714.00
Total Tax Payable in: 129.00
Total Premium Payable In: 843.00
RTO Location: PUNJAB-BATHINDA

‘… has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.’

I´ve been struggling with this problem since yesterday, searching old answers here and even with GPT, but I coudln’t resolve. I’m a beginner at backend I hope you can help me.

I’m developing a simple e-commerce with online payment. I built a server to connect with stripe, My front-end it is at Netlify project and my back-end at Vercel (backend).
backend github
front end github

This is my index.js:

import express from 'express';
import { json } from 'express';
import cors from 'cors';

import router from './stripe.js';
const stripe = router;

const app = express();
app.use(cors());
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

const port =  3000; 

// Middleware to parse JSON and set up
app.use(express.json()); 
app.use(express.urlencoded({ extended: true })); 

app.use("/CartCheckout/stripe", stripe)
app.use(json());

app.get('/', (req, res) => {
  res.send('Servidor do backend está funcionando!');
});

app.post('/create-checkout-session', async (req, res) => {
  const { amount, currency } = req.body;

  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount,
      currency,
    });

    res.status(200).json({ clientSecret: paymentIntent.client_secret });
  } catch (error) {
    console.error('Erro ao criar o pagamento:', error);
    res.status(500).send({ error: 'Erro ao criar o pagamento' });
  }
});

app.listen(port, () => {
  console.log(`Servidor do backend está rodando em http://localhost:${port}`);
});


This is stripe.js:

import express from 'express';
import Stripe from 'stripe';
import { config as configDotenv } from 'dotenv';
configDotenv();

// eslint-disable-next-line no-undef
const STRIPE_API_KEY = process.env.STRIPE_API_KEY;
const stripe = Stripe(STRIPE_API_KEY);

const router = express.Router();

router.post('/create-checkout-session', async (req, res) => {
    const { cartItems } = req.body;
    console.log(cartItems)
    const lineItems = cartItems.map((item) => ({
        price_data: {
            currency: 'brl',
            product_data: {
                name: item.productName,
            },
            unit_amount: parseInt(item.price * 100),
        },
        quantity: item.quantity,
    }));

    console.log(lineItems);

    const session = await stripe.checkout.sessions.create({
        line_items: lineItems,
        mode: 'payment',
        // eslint-disable-next-line no-undef
        success_url: `${process.env.URL}/checkout-success`,
        // eslint-disable-next-line no-undef
        cancel_url: `${process.env.URL}/CartCheckout`,
    });

    res.send({ url: session.url });
});


export default router

vercel.json:

{
    "version": 2,
    "builds": [
      {
        "src": "./index.js",
        "use": "@vercel/node"
      }
    ],
    "headers": [
        {
        "source": "/CartCheckout/stripe/(.*)",
        "headers": [
            { "key": "Access-Control-Allow-Origin", "value": "https://delicias-da-casa.netlify.app" },
            { "key": "Access-Control-Allow-Credentials", "value": "true" },
            { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
            { "key": "Access-Control-Allow-Headers", "value": "Origin, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
        ]
        }
    ]
  }
  

And is working totaly fine on localhost, but when I deployed at Vercel is giving me this error: “… has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”
I tried to enable CORS on vercel with vercel.json and everything (https://vercel.com/guides/how-to-enable-cors#enabling-cors-using-vercel.json) but I couldn’t resolve.

New to A-frame and code, what am I doing wrong?

I’m just trying to import my own glb/gltf model onto a Hiro preset marker code, but been messing with it for days now and absolutely nothing shows up on my marker when I try the website with the camera.
(Boxes and other entities are showing up as normal when I try those etc.)

Here’s the code I have for now, anything I’m doing wrong?

> <html>
  <head>
    <script src="https://aframe.io/releases/1.5.0/aframe.min.js"></script>
    <script src="https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.js"></script>
  </head>

  <body style="margin: 0px; overflow: hidden">
    <a-scene embedded arjs>
      <a-assets>
        <a-asset-item
          src="https://cdn.glitch.global/aa9e51bb-de37-4765-b858-7e9b4af32a3c/Piest.glb?v=1709750576602"
          id="piest"
        >
        </a-asset-item>

        <a-marker-camera preset="hiro"></a-marker-camera>
        <a-entity
          id="#piest"
          src="https://cdn.glitch.global/aa9e51bb-de37-4765-b858-7e9b4af32a3c/Piest.glb?v=1709750576602"
          position="0 1 0"
          scale="1 1 1"
        >
        </a-entity>
        <a-glb-model
          src="https://cdn.glitch.global/aa9e51bb-de37-4765-b858-7e9b4af32a3c/Piest.glb?v=1709750576602"
        >
        </a-glb-model>
        <a-gltf-model
          src="https://cdn.glitch.global/aa9e51bb-de37-4765-b858-7e9b4af32a3c/Piest.glb?v=1709750576602"
          position="1 1 1"
          rotation="0 180 0"
          scale="1 1 1"
        ></a-gltf-model>
        <a-entity src="##piest"> </a-entity>
      </a-assets>
    </a-scene>
  </body>
</html>

Thank you!

Transition delay ignored in loop

There is a component that has fade transition with delay applied. Works as expected unless it is put inside a loop. In that case it ignores the delay property.

Code of the component:

<div in:fade={{ delay: delayPlus(), duration: 1500 }}>
    <p>{word}</p>
</div>

Delay value incrementor:

function delayPlus() {
    let delay: number = 0;
    count.subscribe((value) => (delay = value));
    count.update(() => delay + (Math.floor(Math.random() * 451) + 50));
    return delay;
}

Components are rendered in respect to the delay property when used as:

<div in:fade={{ delay: delayPlus(), duration: 1500 }}>
    <p>{words[0]}</p>
</div>
<div in:fade={{ delay: delayPlus(), duration: 1500 }}>
    <p>{words[1]}</p>
</div>
<div in:fade={{ delay: delayPlus(), duration: 1500 }}>
    <p>{words[2]}</p>
</div>
<div in:fade={{ delay: delayPlus(), duration: 1500 }}>
    <p>{words[3]}</p>
</div>

However if they are rewritten into a loop they appear immediately respecting only the duration property:

{#each words as word}
    <div in:fade={{ delay: delayPlus(), duration: 1500 }}>
        <p>{word}</p>
    </div>
{/each}

Is this a standard behaviour? What is the catch to make the loop behave as expected in first example?

Select a DOM element using Javascript

I have the following snippets of HTML and Javascript.

In the Javascript I have a reference to a button element
from which I want to get a reference to the first element
of class “proof” in the enclosing div element of class “theorem”.

My best attempt so far shown in the Javascript snippet dosen’t work.

Any help will be much appreciated.

<section>   
   <div id="t1" class="theorem">

        <div>
            <span>Theorem   1:</span>
            <button class="toggle">Proof</button>
        </div>  

        <p>
            Text of my Theorem 1.
        </p>

        <div class="proof">
            Proof of my Theorem 1.
        </div>  
        
    </div>
</section>

<script>
    var buttons = document.getElementsByClassName("toggle");
    var i;
    for (i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", function() {
            var theorem = this.closest("theorem");                  
            var proof = parent.querySelector(".proof");
        });
    }
</script>

Put request in NodeJs does not update the task

Controller:

const updateTask =  async(req,res) => {
    try{
        const{id} = req.params;
        const task = await Task.findByIdAndUpdate(
            {_id: id}, req.body, {new: true}
        )
        res.status(200).json(task);

    }catch(error){
        res.status(500).json({msg: error.message})
    }
}

The postman request on sending this does not update the task

I tried everything and I am stuck

Elementor Custom Widget Color Control, get value as string in settings

I try to get the color of the color-control as a string. If I choose the color on the right side at the color-picker, everything works fine.

enter image description here
But

If I use the predefined colors on the left, the color is not updated in the content_template-method (or by the render-method in frontend), but it is shown in the right-side symbol of the color-control. If I click the color-symbol, the color is shown by the content_template method.

enter image description here

If I try selecting predefined colors twice, the default value is used by the content_template-method or the render()
This are the register-controlls(), render() and content_template() methods.

    protected function register_controls() {

        $this->start_controls_section(
                'color_to_show_section',
            [
                'label' => esc_html__( 'Farbe zum aussuchen', 'elementor-as-gmap-widget' ),
                'tab' => ElementorControls_Manager::TAB_CONTENT,
            ]
        );
        $this->add_control(
            'title',
            [
                'type' => ElementorControls_Manager::TEXT,
                'label' => esc_html__( 'Title', 'textdomain' ),
                'placeholder' => esc_html__( 'Enter your title', 'textdomain' ),
            ]
        );

        $this->add_control(
            'landscape_color',
            [
                'label' => esc_html__( 'Color', 'elementor-as-gmap-widget' ),
                'type' => ElementorControls_Manager::COLOR,
                'default' =>    '#ff00ff' ,
            ]
        );

        $this->end_controls_section();



    }


    protected function render() {
        $settings = $this->get_settings_for_display();
        ?>
            <h1> <?php echo $settings['title'] ?></h1>
            <p>Die Farbe: <?php echo $settings['landscape_color'] ?></p>
        <?php
    }


    protected function content_template() {
        ?>
            <h1>{{{settings.title}}}</h1>
            <p>Die Farbe: {{{settings.landscape_color }}}</p>
        <?php
    }

All examples and documentations are about using the color-control to set styles in css, so I wonder, if it is even possible, to get the color as string. But since the normal color-picker works, I think it is possible.
Thanks

Get class name from html if class active

I want a way to get the 1108 in javascript only if class has active state
TML the a element is active, So i am looking for a way to get the number 1108 in javascript

<li :class="category == 1108 ? 'child' : ''" ;="" class="child">
  <a class="child active" @click="filterPosts(1108)">name cat id 1108</a>
</li>

as you can see from the above H

How to determine image format from Base64 encoded string without prefix?

I received a base64 encoded string of an image from a friend, but the string doesn’t include the standard prefix (e.g., “data:image/png;base64,” “data:image/jpeg;base64,” etc.) to indicate the image format. Without this prefix, I’m unable to determine the image format (JPEG, PNG, WebP, etc.).

Can I somehow display the image without knowing the exact image format? I’ve tried appending different prefixes (e.g., “data:image/png;base64,”) to the base64 encoded string and displaying it as an image, but it didn’t work consistently. For example, when the image is encoded in the WebP format but I tried displaying it as PNG, it didn’t show up on the website.

Is there a reliable way to determine the image format from a base64 encoded string without the prefix and display it accordingly? Any suggestions or guidance would be greatly appreciated. Thank you!

excel file is not being picked and not readable as well in expo reactnative

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
import { DocumentDirectoryPath } from 'react-native-fs'; // Import DocumentDirectoryPath from react-native-fs

export default function App() {
  const getDocs = async () => {
    try {
      const res = await DocumentPicker.getDocumentAsync({
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
       console.log(res.uri)


      if (res.type === 'success' && res.uri) {
        const filePath = res.uri; // Use the URI directly, no need to construct file path
        const fileContent = await readFile(filePath, 'base64');
        console.log('File content:', fileContent);
      }
    } catch (error) {
      console.error('Error while picking the file', error);
    }
return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <Button title='Go To Gallery' onPress={getDocs}/>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

i used this code but file uri is something like this:file:///data/user/0/host.exp.exponent/cache/DocumentPicker/57d6add2-1bc6-4cca-90d1-185864d83c79.xlsx which is not been readed this file uri i got from the console.log(res.uri). needs the expert decisions in few of my questions:

  • is expo document picker is oky to use or third party react native document picker?
  • path is being picked but further not readable why?
  • i used the third party react native document picker but got errors of appregistry and main got failed to load module ?
  • main output i want to read the excel file from the documets folder and shows the data in tables…

i am building an app which should show the excel file data where i further want to do analysis but got stuck here