Why does my Expo-Camera function not open for my app in Expo Go?

I’m trying to open a camera as part of my app. I am using Expo Go to open this app on my IOS device, coded using React Native. However, I get this error:

(NOBRIDGE) ERROR  Warning: TypeError: _expoCamera.Camera.useCameraPermissions is not a function (it is undefined)

This is CameraScreen.js.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { Camera } from 'expo-camera';

export default function CameraScreen() {
  const [permission, requestPermission] = Camera.useCameraPermissions();
  const [cameraType, setCameraType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    if (!permission) {
      requestPermission(); // Request permissions on mount if not granted
    }
  }, [permission]);

  if (!permission) {
    // Permissions are still loading
    return <View style={styles.container}><Text>Loading...</Text></View>;
  }

  if (!permission.granted) {
    // Permission is not granted yet
    return (
      <View style={styles.container}>
        <Text style={{ textAlign: 'center' }}>
          We need your permission to access the camera.
        </Text>
        <Button onPress={requestPermission} title="Grant Permission" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Camera style={styles.camera} type={cameraType} />
      <Button
        title="Switch Camera"
        onPress={() =>
          setCameraType((prev) =>
            prev === Camera.Constants.Type.back
              ? Camera.Constants.Type.front
              : Camera.Constants.Type.back
          )
        }
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16,
  },
  camera: {
    flex: 1,
    width: '100%',
  },
});

I have these permissions in package.json.

    },
    "ios": {
      "supportsTablet": true,
      "newArchEnabled": true,
      "infoPlist": {
        "NSCameraUsageDescription": "We need access to your camera to take photos."
      }
    },
    "android": {
      "newArchEnabled": true,
      "adaptiveIcon": {
        "foregroundImage": "./assets/adaptive-icon.png",
        "backgroundColor": "#ffffff"
      },
      "permissions": ["CAMERA"]
    },
    "plugins": [
      [
        "expo-camera",
        {
          "cameraPermission": "Allow $(PRODUCT_NAME) to access your camera",
          "microphonePermission": "Allow $(PRODUCT_NAME) to access your microphone",
          "recordAudioAndroid": true
        }
      ]

From my understanding, the babel.config.js must also be modified correctly so I have included it below in case.

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: ["module:react-native-dotenv"],  // Use "module:react-native-dotenv"
  };
};

If relevant, these are the relevant parts of the code for my HomePage.js and App.js:

    <TouchableOpacity style={styles.cameraButton} onPress={openCamera}>
        <Text style={styles.cameraButtonText}>+</Text>
      </TouchableOpacity>
      <TouchableOpacity
  <Stack.Screen name="Camera" component={CameraScreen} options={{ title: 'Camera' }} />

Appreciate your clarifications.

Edited to add dependencies if the issue is there, which I personally suspect is the case. Perhaps I am using the wrong versions or versions that are not compatible with each other?

  "dependencies": {
    "@babel/plugin-proposal-export-namespace-from": "^7.18.9",
    "@expo/vector-icons": "^14.0.2",
    "@react-navigation/native": "*",
    "@react-navigation/stack": "*",
    "@supabase/supabase-js": "^2.46.1",
    "axios": "^1.7.9",
    "babel-plugin-module-resolver": "^5.0.2",
    "expo": "^52.0.17",
    "expo-camera": "~16.0.9",
    "expo-keep-awake": "^14.0.1",
    "expo-status-bar": "~2.0.0",
    "glob": "^11.0.0",
    "metro-config": "^0.81.0",
    "postcss": "^8.4.49",
    "react": "18.3.1",
    "react-native": "^0.76.3",
    "react-native-dotenv": "^3.4.11",
    "react-native-gesture-handler": "~2.20.2",
    "react-native-paper": "4.9.2",
    "react-native-reanimated": "^3.16.3",
    "react-native-safe-area-context": "4.12.0",
    "react-native-screens": "~4.1.0",
    "react-native-svg": "15.8.0",
    "rimraf": "^6.0.1",
    "tailwind-rn": "^4.2.0",
    "tailwindcss": "^3.4.16"

Getting an error when using FullCalendar React library

I tried to implement a React calendar with local storage and the FullCalendar library using the below code.

<FullCalendar 
    plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]} 
    initialView="timeGridWeek"
    headerToolbar={{           
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
    }}
    events={calendarEvents}
    editable={true}
    eventClick={handleEventClick}
/>

However, I’m getting the following error:

Error: 'FullCalendar' cannot be used as a JSX component.
Its type 'typeof FullCalendar' is not a valid JSX element type.
Type 'typeof FullCalendar' is not assignable to type 'new (props: any, deprecatedLegacyContext?: any) => Component<any, any, any>'.
Type 'FullCalendar' is missing the following properties from type 'Component<any, any, any>': context, setState, forceUpdate, props, refs

The suggested posts just offer specific solutions but not the general approach to this issue.

auto fill : “Value is required” even though there is a value in the form field

I am using a plugin to autofill workday job application:

content script:

    // Fill the First Name
    const firstNameInput = document.querySelector('[data-automation-id="legalNameSection_firstName"]');
    if (firstNameInput) {
        firstNameInput.value = 'First Name'; 
        firstNameInput.focus();

    }

    // Fill the Last Name
    const lastNameInput = document.querySelector('[data-automation-id="legalNameSection_lastName"]');
    if (lastNameInput) {
        lastNameInput.value = 'Last Name'; 
        lastNameInput.focus();
    }

    const address_1 = document.querySelector('[data-automation-id="addressSection_addressLine1"]');
    if (address_1) {
        address_1.value = 'address1'; 
        address_1.focus();
    }
    const address_2 = document.querySelector('[data-automation-id="addressSection_addressLine2"]');
    if (address_2) {
        address_2.value = 'address2'; 
        address_2.focus();
    }
    const postalCode = document.querySelector('[data-automation-id="addressSection_postalCode"]');
    if (postalCode) {
        postalCode.value = '0000'; 
        postalCode.focus();
    }

    const city = document.querySelector('[data-automation-id="addressSection_city"]');
    if (city) {
        city.value = 'Hong Kong'; 
        city.focus();
    }
    
    const phoneNumber = document.querySelector('[data-automation-id="phone-number"]');
    if (phoneNumber) {

        phoneNumber.value = '1234 5678'; 
        phoneNumber.focus();

    }

enter image description here

I tried rearranging the order of filling and focusing on those elements.

Only the last element doesn’t have this issue.

I tried rearranging the order of filling and focusing on those elements.

Only the last element doesn’t have this issue.

Correction of Incorrect Date in the Umm al-Qura Calendar [closed]

After careful observation it has become apparent that the date shown for [04-06-1446] does not align with the expected the correct lunar cycle. I kindly request that you review the data and make any necessary adjustments to ensure that the calendar reflects the accurate and correct date.

**how to correct date in the following (link) scripts, please suggest to make correction where needed **

https://github.com/Ahmed-Raouf/ummalqura-calendar

Hijri Date Numeric | 6-06-1446
(But show in calendar 05-06-1446)

Today is | Saturday Today Gregorian Date Numeric | 7-12-2024

Is it a leap year? | 2024 It’s not a leap year

Julian Date | 2460652

How can I define the Return Type of my function

I have a function that either returns an array if everything is ok or else returns an object with error = true and errMsg, how can I define the return type of my function

what I defined till now

searchFn: (value: string) => Promise<{ error?: boolean }>;

My function –

const [data, setData] = useState([])
let result = await searchFn(id);
if (result?.error) {
  log(result.error)
} 
else {
  log(result)
  setData(result)
}

and my search function

const res = await fetch()
if (!res.ok) return { error: true, errMsg: errMsg };
return await res.json();

Am I doing this correctly, can you please help with the type definition of the searchFn

Thanks

Trpc nextjs problems on build when implenting promethus

I am runing a classic nextjs with t3 stack and trpc, when i am implemnting prom using prom-client and trpc middleware everything runing locally .

when i run npm run build all the custom metric does not update any more.

my file structure is
/lib/metric/prom.ts

import {register, Counter, Histogram} from 'prom-client';// dynamic?

export  const httpRequestCounter = new Counter({
    name: 'http_requests_total',
    help: 'Total number of HTTP requests',
    labelNames: ['method', 'procedure', 'status_code'],
  });

export const responseTimeHistogram = new Histogram({
    name: 'http_response_time_seconds',
    help: 'Response time in seconds',
    labelNames: ['method', 'procedure'],
  });


register.registerMetric(httpRequestCounter);
register.registerMetric(responseTimeHistogram);


/api/metrics/route.ts

/* eslint-disable */
// @ts-ignore
import { NextResponse } from 'next/server';
import {register} from 'prom-client'
// import dynamic from 'next/dynamic';
//
// @ts-ignore
// const metrics: {register: {contentType: string, metrics: () => {}} } = dynamic(() => import('@/lib/metrics/promethus'), { ssr: false });

import metrics from '@/lib/metrics/promethus'

export async function GET() {
  try {
    const data = await register?.metrics();
    return new NextResponse(data, {
      status: 200,
      headers: { 'Content-Type': register.contentType },
    });
  } catch (error) {
    console.error('Error generating metrics:', error);
    return new NextResponse('Unable to generate metrics', { status: 500 });
  }
}
export const dynamic ='force-dynamic'

/server/api/trpc.ts <-middleware here .

const metricsMiddleware = t.middleware(async ({ path, type, next }) => {
  const endTimer = responseTimeHistogram.startTimer({
    method: type,
    procedure: path,
  });

  // todo: fix servers the thest again might ahve solution
  try {
    const result = await next();

    console.log(' am i here???')
    // Map tRPC result to an HTTP status code
    let statusCode = '200';
    if (!result.ok) {
      // Map specific tRPC error codes to HTTP status codes if needed
      statusCode = '500';
    }

    console.log('before requests')
    httpRequestCounter.inc({
      method: type,
      procedure: path,
      status_code: statusCode,
    });

    console.log("after request")
    return result;
  } catch (error) {
    // Handle unexpected errors
   httpRequestCounter.inc({
      method: type,
      procedure: path,
      status_code: '500',
    });

    throw error;
  } finally {
    endTimer();
  }
});

any direction will be appreciated.

I tried to implement as detailed above, i tried singleton patterns and whatnot but nothing seemed to work, i tried preventing the pap from static loading the prom file,
i expected the metric reporting to work same as on local dev but i just cant get it to work.

TypeScript Error in Express Route: “No Overload Matches This Call”

Question:

I am developing an e-commerce platform using TypeScript with Express. Below is the code snippet and the error I am facing. How can I fix this issue, and why does the solution work?

Code Snippets:

User Router:

router.post('/user/:id/add-address', async (req: Request<IAddress>, res: Response) => {
  try {
    const address = await Address.create(req.body);
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { $push: { address: address._id } },
      { new: true }
    );

    if (!user) {
      return res.status(404).json({
        success: false,
        message: 'User not found'
      });
    }

    return res.status(200).json({ message: 'Address added successfully', user });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: 'Error adding address' });
  }
});

Interfaces:

  1. IAddress:
import { Document } from "mongoose";

export default interface IAddress extends Document {
  name?: string;
  lastName?: string;
  email?: string;
  street: string;
  city: string;
  state: string;
  zipcode: number;
  country: string;
  phone: number;
}
  1. IUser:
import mongoose from "mongoose";

export default interface IUser {
  name: string;
  email: string;
  password: string;
  phoneNumber?: string;
  address?: mongoose.Schema.Types.ObjectId[];
  wishlist?: mongoose.Schema.Types.ObjectId[];
  cart?: mongoose.Schema.Types.ObjectId[];
  orderHistory?: mongoose.Schema.Types.ObjectId[];
  paymentMethods?: mongoose.Schema.Types.ObjectId[];
  createdAt?: Date;
  updatedAt?: Date;
}

Error:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request<IAddress>, res: Response) => Promise<express.Response<any, Record<string, any>>>' is not assignable to parameter of type 'Application<Record<string, any>>'.
      Type '(req: Request<IAddress, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>) => Promise<...>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more.ts(2769)
index.d.ts(164, 5): The last overload is declared here.
(parameter) req: express.Request<IAddress, any, any, QueryString.ParsedQs, Record<string, any>>

Solution:

I got the following solution:

router.post('/user/:id/add-address', async (req: Request<IAddress>, res: Response): Promise<any> => {
  // Function logic
});

Question:

Why does adding the explicit Promise<any> type fix the issue? Could you explain the reasoning behind this solution?

How can I generate markup for dynamic content in a React Native app?

I’m building a React Native app with dynamic content, and I want to ensure the app generates SEO-friendly markup for search engines. Given that React Native does not natively support server-side rendering, I am investigating methods to optimize the app for crawlers with limited JavaScript support.

I’ve Tried

  1. Static Markup with Rendertron:
    I used Rendertron to pre-render pages for search engine crawlers. While it works, it adds complexity to the deployment process, and I’m struggling to dynamically update metadata for each page.

  2. Meta Tags and Open Graph:
    I implemented meta tags and Open Graph tags, but I suspect they’re not sufficient for search engines that don’t fully render JavaScript content.

  3. Exploring Alternatives to SSR:
    I’ve read about alternatives like pre-rendering static content during build time but couldn’t find a clear approach tailored for React Native apps.

My Questions

  1. How can I generate SEO-friendly static or pre-rendered markup for a React Native app with dynamic content?

  2. Are there any tools or libraries specifically designed for SEO optimization in React Native apps?

  3. What’s the best way to handle dynamic metadata updates for SEO purposes?

How Can I Display Only Parent Categories on WordPress?

I’m working with this directory site theme and in the search function, it has the “Search by: Category” option.

I’d like to rename that to “Search by: Location” and when people click the drop-down, it should only display the parent categories, which are the location names. It should not show any of the sub-categories.

here’s the code…

        <div class="col-lg-4">
        <div class="dropdown dropdown-category">
            <select name="dropdown_category4" class="btn btn-secondary dropdown-toggle" type="button" id="listing_category">
                <option value="" selected><?php _e('Search by: Category', 'directorytheme'); ?></option>
                <?php
                $terms_links = get_terms('listing-categories');
                foreach( $terms_links as $terms_link ) { ?>
                    <option class="dropdown-item dropdown-cat" value="<?php echo "{$terms_link->slug}"; ?>"><?php echo "{$terms_link->name}"; ?></option>
                <?php
                } ?>
            </select>
            <?php 
                if($listing_category != ''){ 
            ?>
                    <input type="hidden" name="s_listing_category" id="s_listing_category" value ="<?php echo $listing_category; ?>">
            <?php } else { ?>
                    <input type="hidden" name="s_listing_category" id="s_listing_category">
            <?php } ?>
        </div><!--dropdown-->
    </div>

How can I modify it to do what I need it to do?

Thanks!

How to *Accumulate* Consecutive `scrollBy` Calls with `behavior: “smooth”` for Smooth Scrolling?

Background

I’m implementing a feature where pressing Alt enables scrolling 5x faster, similar to the behavior in VSCode. Below is the relevant code snippet (full code can be found at CodePen):

/**
     * Scrolling speed multiplier when pressing `Alt`.
     * @type {number}
     */
    const fastScrollSensitivity = 5;
    function findScrollableElement(e, vertical = true, plus = true) {
        // -- Omitted --
    }
    /**
     * Handle the mousewheel event.
     * @param {WheelEvent} e The WheelEvent.
     */
    function onWheel(e) {
        if (!e.altKey || e.deltaMode !== WheelEvent.DOM_DELTA_PIXEL) return;
        e.preventDefault();
        e.stopImmediatePropagation();
        const { deltaY } = e;
        const amplified = deltaY * fastScrollSensitivity;
        const [vertical, plus] = [!e.shiftKey, e.deltaY > 0];
        const el = findScrollableElement(e, vertical, plus);
        Object.assign(lastScroll, { time: e.timeStamp, el, vertical, plus });
        el.scrollBy({
            top: e.shiftKey ? 0 : amplified,
            left: e.shiftKey ? amplified : 0,
            behavior: "instant"
        });
        // TODO: Smooth scrolling
    }
    /**
     * Enable or disable the fast scroll feature.
     * @param {boolean} enabled Whether the fast scroll feature is enabled.
     */
    function fastScroll(enabled) {
        if (enabled) {
            document.addEventListener("wheel", onWheel, { capture: false, passive: false });
        } else {
            document.removeEventListener("wheel", onWheel, { capture: false, passive: false });
        }
    }

The feature works as expected when using behavior: "instant" in scrollBy. However, switching to behavior: "smooth" causes issues.


Question

The issue arises when I use behavior: "smooth". If scrollBy is called repeatedly before the previous animation ends, the subsequent call seems to interrupt the ongoing animation, leading to inconsistent behavior and slower scrolling speeds.

  1. Is it possible to let the browser accumulate consecutive scrollBy calls instead of cancelling previous ones?
  2. If not, how can I modify my code to enable smooth scrolling without these issues?

I prefer having the browser handle the smooth animations rather than manually calculating and animating via JavaScript.


Attempts

  1. Using scrollBy with behavior: "smooth"

    • Problem: Consecutive calls interrupt previous animations.
  2. Accessing scrollTop

    • Problem: When accessed before the animation ends, it returns intermediate values, which makes calculations unreliable.
  3. Smooth scrolling with requestAnimationFrame (considered but not implemented)

    • I want to avoid handling smooth animations manually if possible.

Anyone knows how to use lifecycle hooks in Strapi 5?

I didn’t find the documentation that explains this in Strapi 5, so i don’t know if it changed since Strapi 4.

path of the code: src/api/post/content-types/post/lifecycle.js

const axios = require('axios');

module.exports = {
    async afterCreate(event) {
        await axios.post('https://api.netlify.com/build_hooks/key');
    },

    async afterUpdate(event) {
        await axios.post('https://api.netlify.com/build_hooks/key');
    },
}

When you use the method post on this link, netlify will automatic build your application with the new content. but it’s not working

Update the css-loader v7, and imported module became undefined

I have script like this and it works well until today,

import styles from '../css/basic-styles.module.css';
 <div className={styles.wrapper}

However, suddeenly this code shows the error on console,

Maybe It’s related with the updating some library by ncu???

"css-loader": "^6.7.3", ->     "css-loader": "^7.1.0",

then error is

TopPage.js:2811 Uncaught TypeError: Cannot read properties of undefined (reading 'wrapper')
    at TopPage (TopPage.js:2811:86)

So I guess it means import module doesn’t work correctly.

Now I add the code and test,

import styles from '../css/basic-styles.module.css';
console.log(styles) // undefined.

I have webpack.config.js

const path = require("path");
const webpack = require("webpack");

module.exports = {
   entry: "./src/index.js",
   output: {
       path: path.resolve(__dirname, "./static/frontend"),
       filename: "[name].js",
   },

   module: {
       rules: [
           {
               test: /.js$/,
               exclude: /(node_modules|bower_components)/,
               use: {
                   loader: "babel-loader",
                   options: {
                    presets: ['@babel/preset-react', '@babel/preset-env']
                  }
               },
            },
            {
                test: /.css/,
                use: [
                    "style-loader",
                    {
                        loader: 'css-loader'
                    }
                ]
            },
            {
                test: /.(png|jpg|gif|svg|fbx|obj|mtl)/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            //[name]は画像名、[ext]は拡張子
                            name: 'images/[name].[ext]'
                        }
                    }
                ]
            }
       ],
   },
   optimization: {
       minimize: true,
   },
   plugins: [
       new webpack.DefinePlugin({
           'process.env.NODE_ENV' : JSON.stringify('development')
       })
   ]
}

my ces is like this below.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
 
}

h1 {
  text-align: center;
  margin: 2rem 0 4rem 0;
}
.btnSeparator{
  height:30px
}

.overlayConfirmAlert{
  z-index: 10001;
}
.drawingSuggests{
  overflow-y:auto;
 
  height:calc(100vh - 335px);
}

Where should I check?

How should I create a comment section for a Github Website?

I’m looking to create a basic comment section for my website and need a hand. I don’t want anything as complex as a login system, but I want to at least be able to reload the page and still see the comment. I know there are things like utterance that can help me, and I’m willing to figure out how to do that if that’s the easiest answer.
I know html, css, and a little bit of sql but I’m not sure if that’ll help me here. I can kind of pick apart javascript but I haven’t taken that class yet. But again, I’m willing to learn some things to get this to work.

I originally thought that maybe I could use javascript to just edit the html file, but I wasn’t able to find anything on that.
I also looked into connecting a database to my github repository, but research made it seem as though it would be really dangerous because connecting to the database would require my username and password and you can’t keep that kind of information on the front end or it could be stolen. And I didn’t understand what I needed to do to code on the backend.
I was also thinking of maybe learning how to code in XML and have the javascript edit that file, because I saw something about a language called XMLDOM that looked like it could do what I wanted, then have the html file draw on the XML file for the comment section, but around that point I figured it would be a lot less stressful to just ask and see if I’m even heading in the right direction or if there’s a simple solution that I just missed.

<div id="comment_box">
    <h2>Comments</h2>
    <div class="comment">
        <p class="commenter">Tyson</p>
        <p>Love it!</p>
    </div>
</div>

Adding a comment should just add another div.comment with two p elements in it.

My code seems correct but my syntax error says I am missing a semicolon

iOS Bundling failed 6688ms node_modulesexpoAppEntry.js (650 modules)
ERROR SyntaxError: C:UsersmeDesktopWeightLiftingAppApp.js: Missing semicolon. (1:4)

This is the code in question:

import React from "react";
import { View, Text } from "react-native";

export default function App() {
    return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
            <Text>Hello, World!</Text>
        </View>
    );
}

I pasted it into notepad to see if their were any invisible characters causing issues and expected to find some but found nothing