This is expo ReactNative App. Able to build and run the app using
expo start
However, InteliJ Flags this file as having an error and all this file has is the above referenced code
import { ButtonActionTypes } from "../types/ButtonTypes";
import { Action } from "redux";
export const incrementCount = (): Action<string> => {
return {
type: ButtonActionTypes.Increment
}
};
How do I get rid of this error so the project in InteliJ looks clean?
Related
In my T3 stack app, next js middleware is not triggering,
I have created middelware.ts file in root directory.
middleware.ts
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
console.log("middleware calling");
return NextResponse.redirect(new URL("/login/:path*", request.url));
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ["/products/:path*", "/login/:path*"],
};
I haven't seen any redirection or console log,
Anyone know why this is happning?
Thanks!
I have referred Next js Docs and some medium docs.
I got the fix,
It's just that I have renamed middleware.ts to middleware.page.ts
The Problem:
I'm building a blog with Next and sanity. When navigating to /blog, i'm encountering this error in the browser:
./sanity.js:2:0
Module not found: Can't resolve '#sanity/image-url'
1 | import { createCurrentUserHook, createClient } from "next-sanity";
> 2 | import imageUrlBuilder from "#sanity/image-url";
3 |
4 | export const config = {
5 | // Find your project ID and dataset in 'sanity.json' in your studio project.
Import trace for requested module:
./pages/blog.tsx
https://nextjs.org/docs/messages/module-not-found
The folder structure is:
root
-> components
-> pages
-> post
-> [slug].tsx
-> index.tsx
-> blog.tsx
-> sanity subfolder
-> public
-> styles
sanity.js (config file)
The sanity config file
I have a sanity config file, which exports some helper functions. One of which, is the imageUrlBuilder function, which i'm assuming the error is coming from. Here is my sanity config file: Note: this is pulled from sanity docs.
import { createCurrentUserHook, createClient } from "next-sanity";
import imageUrlBuilder from "#sanity/image-url";
export const config = {
// config info here
};
// Set up the client for fetching data in the getProps page functions.
export const sanityClient = createClient(config);
// Builder function to combo with urlFor function.
const builder = imageUrlBuilder(sanityClient);
// Helper function to generate urls from sanity photos.
export const urlFor = (source) => {
return builder.image(source);
};
The helper function was working in a previous version, and was able to pull images from sanity and display in the document. But i'm unsure why it's causing issues with page routing.
The blog page component:
import React from "react";
import BlogPreview from "../components/BlogPreview";
import { getAllPosts } from "../queries";
import { sanityClient } from "../sanity";
import { Post } from "../typings";
interface Props {
posts: [Post];
}
// required for server-side rendering. returns 'props' object from db.
export const getServerSideProps = async () => {
let query = getAllPosts;
const posts = await sanityClient.fetch(query);
return {
props: {
posts,
},
};
};
function blog({ posts }: Props) {
return (
<div>
<div className='md:grid md:grid-cols-2'>
{posts.map((post) => {
return (
<BlogPreview
key={post._id}
title={post.title}
description={post.description}
mainImage={post.mainImage}
slug={post.slug}
/>
);
})}
</div>
</div>
);
}
export default blog;
I've tried:
Logging sanity data to the console to check for config errors.
Googling the error: Module not found: Can't resolve '#sanity/image-url'
Conclusion
I'm unsure what the issue is, and how I can potentially solve it. Would love some ideas.
Thanks in advance
It sounds like you don't have the #sanity/image-url module installed in your project.
Run this in your project directory and you should be good to go!
npm install --save #sanity/image-url
Trying to create an xterm react component in Next.js I got stuck as I'm not able to get over an error message I've never got before.
I'm trying to import a npm client-side module called xterm, but if I add the import line the application crashes.
import { Terminal } from 'xterm'
The error reads Server Error... ReferenceError: self is not defined
and then shows this chunk of code as Source
module.exports = require("xterm");
According to some research I did, this has to do with Webpack and could be helped if something like this was done:
output: {
globalObject: 'this'
}
Would you know how to fix this?
The error occurs because the library requires Web APIs to work, which are not available when Next.js pre-renders the page on the server-side.
In your case, xterm tries to access the window object which is not present on the server. To fix it, you have to dynamically import xterm so it only gets loaded on the client-side.
There are a couple of ways to achieve this in Next.js.
#1 Using dynamic import()
Move the import to your component's useEffect, then dynamically import the library and add your logic there.
useEffect(() => {
const initTerminal = async () => {
const { Terminal } = await import('xterm')
const term = new Terminal()
// Add logic with `term`
}
initTerminal()
}, [])
#2 Using next/dynamic with ssr: false
Create a component where you add the xterm logic.
// components/terminal-component
import { Terminal } from 'xterm'
function TerminalComponent() {
const term = new Terminal()
// Add logic around `term`
return <></>
}
export default TerminalComponent
Then dynamically import that component when using it.
import dynamic from 'next/dynamic'
const TerminalComponent = dynamic(() => import('<path-to>/components/terminal-component'), {
ssr: false
})
As an alternative, you could add the logic directly when dynamically importing the library with next/dynamic to avoid having an extra file for it.
import dynamic from 'next/dynamic'
const Terminal = dynamic(
{
loader: () => import('xterm').then((mod) => mod.Terminal),
render: (props, Terminal) => {
const term = new Terminal()
// Add logic with `term`
return <></>
}
},
{
ssr: false
}
)
I am trying to use the expo-camera for web. For reference, this is working 100% on Expo Go on my phone. But when I visit my website (hosted on AWS) which has the same build, I get a white screen after accepting camera permissions because of this error
Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons: 1. You might have mismatching versions of React and the
renderer (such as React DOM) 2. You might be breaking the Rules of
Hooks 3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.
I can see in chrome tools (attached to my phone) this error, but it doesn't look like anything I am doing..
react-native-logs.fx.ts:34 Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at V (react.production.min.js:19)
at Object.t.useRef (react.production.min.js:25)
at ExponentCamera.web.tsx:30
at na (react-dom.production.min.js:157)
at Ia (react-dom.production.min.js:176)
at Bs (react-dom.production.min.js:271)
at Sl (react-dom.production.min.js:250)
at _l (react-dom.production.min.js:250)
at wl (react-dom.production.min.js:250)
at dl (react-dom.production.min.js:243)
And this is the code it is referring to, which is of course part of expo
const ExponentCamera = React.forwardRef(
(
{ type, pictureSize, poster, ...props }: CameraNativeProps & { children?: React.ReactNode },
ref: React.Ref<ExponentCameraRef>
) => {
const video = React.useRef<HTMLVideoElement | null>(null);
const native = useWebCameraStream(video, type as CameraType, props, {
onCameraReady() {
if (props.onCameraReady) {
props.onCameraReady();
}
},
onMountError: props.onMountError,
});
Here is my code
import React from 'react';
import { StyleSheet, Text } from 'react-native';
import { NavigationProp, ParamListBase } from '#react-navigation/native';
import { BarCodeScanningResult, Camera, PermissionResponse, PermissionStatus } from 'expo-camera';
export interface BarCodeScannerScreenProps {
navigation: NavigationProp<ParamListBase>
}
export const BarCodeScannerScreen = (props: BarCodeScannerScreenProps) => {
const [cameraPermission, setCameraPermission] = React.useState<string>(PermissionStatus.UNDETERMINED);
const getPermission = async () => {
const response: PermissionResponse = await Camera.requestCameraPermissionsAsync();
setCameraPermission(response.status);
};
const onBarCodeScanned = (event: BarCodeScanningResult) => {
props.navigation.navigate("BookSearch", {searchValue: event.data});
};
React.useEffect(() => {
getPermission();
}, []);
if(cameraPermission === PermissionStatus.UNDETERMINED){
return <Text>Requesting camera permission</Text>;
}
else if(cameraPermission === PermissionStatus.GRANTED){
return (
<Camera
onBarCodeScanned={onBarCodeScanned}
style={StyleSheet.absoluteFill}
/>
);
}
else {
return <Text>No access to camera</Text>;
}
}
Maybe I do have some invalid hook or something in my code? But I don't see why it would work fine on Expo Go.
The recipe from a React issue comment worked for me:
expo customize:web
select webpack (PRESS SPACE)
enter
Then modify webpack.config.js file this way:
const createExpoWebpackConfigAsync = require('#expo/webpack-config');
const path = require('path');
module.exports = async function (env, argv) {
const config = await createExpoWebpackConfigAsync(env, argv);
// Customize the config before returning it.
config.resolve.alias = {
react: path.resolve('./node_modules/react')
}
return config;
};
I do use recoil in my nextjs application.
But if I run next (in dev or production make no difference) I got this error-message:
Duplicate atom key "companyData". This is a FATAL ERROR in
production. But it is safe to ignore this warning if it occurred because of
hot module replacement.
This is the way I've implemented it:
/src/stores/CompanyStore.js:
import { useSetRecoilState, useRecoilValue , atom } from 'recoil';
import config from '../../content/config.yml';
const companyData = atom({
key: 'companyData',
default: {...config.company},
});
export const useSetCompanyData = () => useSetRecoilState(companyData);
export const useCompanyData = () => useRecoilValue(companyData);
export default {
useSetCompanyData,
useCompanyData,
};
I use it like this in some components:
MyComponent.js
import React from 'react';
...
...
import {useCompanyData} from '../stores/CompanyStore';
const MyComponent = () => {
const classes = useStyles();
const companyData = useCompanyData();
const { summary: headline, description } = companyData;
return (<div><h2>{headline}</h2><p>{description}</p>)
I don't see, why this error-message appears. Might it caused of a bug in nextjs, or did I implement recoil in a wrong way?
Looks like a problem with recoil in nextjs when you have state in a separate file:
https://github.com/facebookexperimental/Recoil/issues/733
As of Recoil 0.7.6, add RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED=false to your environment to hide these warnings.
(roeland had the correct GitHub issue, which has since been closed)