Facing Issue : Warning: React.createElement: type is invalid -- expected a string - node.js

I'm using useReducer, Context and Provider in my app but I'm facing this issue please anyone faced this issue so please let me know the solution for it
Warning: React.createElement: type is invalid -- expected a string
(for built-in components) or a class/function (for composite
components) but got: %s.%s%s, undefined, You likely forgot to export
your component from the file it's defined in, or you might have mixed
up default and named imports.
Check your code at App.js:20.,
in _default (at withExpoRoot.js:20)
in RootErrorBoundary (at withExpoRoot.js:19)
in ExpoRootComponent (at renderApplication.js:35)
in RCTView (at View.js:45)
in View (at AppContainer.js:98)
in RCTView (at View.js:45)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:34)
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:26:24 in error
- node_modules\react\cjs\react.development.js:188:36 in warningWithoutStack
- node_modules\react\cjs\react.development.js:603:32 in warning
- node_modules\react\cjs\react.development.js:1730:14 in createElementWithValidation
* App.js:20:5 in _default
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:9473:27
in renderWithHooks
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:11994:6
in mountIndeterminateComponent
- ... 18 more stack frames from framework internals
Warning: React.createElement: type is invalid -- expected a string
(for built-in components) or a class/function (for composite
components) but got: %s.%s%s, undefined, You likely forgot to export
your component from the file it's defined in, or you might have mixed
up default and named imports.
Check your code at App.js:20.,
in _default (at withExpoRoot.js:20)
in RootErrorBoundary (at withExpoRoot.js:19)
in ExpoRootComponent (at renderApplication.js:35)
in RCTView (at View.js:45)
in View (at AppContainer.js:98)
in RCTView (at View.js:45)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:34)
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:26:24 in error
- node_modules\react\cjs\react.development.js:188:36 in warningWithoutStack
- node_modules\react\cjs\react.development.js:603:32 in warning
- node_modules\react\cjs\react.development.js:1730:14 in createElementWithValidation
* App.js:20:5 in _default
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:9473:27
in renderWithHooks
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:11994:6
in mountIndeterminateComponent
- ... 21 more stack frames from framework internals
Invariant Violation: Element type is invalid: expected a string (for
built-in components) or a class/function (for composite components)
but got: undefined. You likely forgot to export your component from
the file it's defined in, or you might have mixed up default and named
imports.
Check the render method of _default.
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:5716:10
in createFiberFromTypeAndProps
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:5744:4
in createFiberFromElement
- ... 22 more stack frames from framework internals
Warning: %s: Error boundaries should implement
getDerivedStateFromError(). In that method, return a state update to
display an error message or fallback UI., RootErrorBoundary
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:26:24 in error
- ... 28 more stack frames from framework internals
App.js
import React from 'react';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import IndexScreen from './src/screens/IndexScreen';
import { Provider } from './src/context/BlogContext';
const navigator = createStackNavigator({
Index: IndexScreen
}, {
initialRouteName: 'Index',
defaultNavigationOptions: {
title: 'Blogs'
}
});
const App = createAppContainer(navigator);
export default () => {
return (
<Provider>
<App />
</Provider>
);
};
BlogContext.js
import React, { useReducer } from 'react';
export default (reducer, actions, initialState) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const boundActions = {};
for(let key in actions){
boundActions[key] = actions[key](dispatch);
}
return(
<Context.Provider value={{state, ...boundActions}}>
{children}
</Context.Provider>
);
}
return(Context, Provider);
};

You have an issue regarding BlogContext. You are not using it correctly.
You export it as default a function while in App.js, you use a named import.
BlogContext should be like this:
import React, { useReducer } from 'react';
export default (reducer, actions, initialState) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const boundActions = {};
for(let key in actions){
boundActions[key] = actions[key](dispatch);
}
return(
<Context.Provider value={{state, ...boundActions}}>
{children}
</Context.Provider>
);
}
//return an object with two keys
return {Context, Provider};
};
and App.js should use that accordingly:
import blogContext from './src/context/BlogContext';
/**
...code ...
**/
//here you create your provider by calling the function imported from BlogContext
//with the expected arguments
const { Provider } = blogContext(reducer, actions, initialState)
/**
**/
export default () => {
return (
<Provider>
<App />
</Provider>
);
};

Related

Error: Invalid `paths` value returned from getStaticPaths (without any changes on files) Slug

iam recently receiving this error message without any changes to files. I deleted some products and categories via the webGUI which might cause this?
Environment is:
Frontend: React, Next.js, TypeScript & Tailwind
Backend: Laravel
Error:
> Build error occurred
Error: Invalid `paths` value returned from getStaticPaths in /category/[slug].
`paths` must be an array of strings or objects of shape { params: [key: string]: string }
at buildStaticPaths (/var/www/domain/node_modules/next/dist/build/utils.js:490:15)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async /var/www/domain/node_modules/next/dist/build/utils.js:615:119
at async Span.traceAsyncFn (/var/www/domain/node_modules/next/dist/telemetry/trace/trace.js:60:20) {
type: 'Error'
}
Category Slug tsx content:
import Container from "#components/ui/container";
import { getLayout } from "#components/layout/layout";
import Subscription from "#components/common/subscription";
import CategoryBanner from "#containers/category-banner";
import { useRouter } from "next/router";
import CategoryProductsGrid from "#components/category/category-products-grid";
export { getStaticPaths, getStaticProps } from "#framework/ssr/category";
export default function Category() {
const { query } = useRouter();
return (
<div className="border-t-2 border-borderBottom">
<Container>
<CategoryBanner className="my-4"/>
<div className="pb-16 lg:pb-20">
<CategoryProductsGrid
classname="3xl:grid-cols-6"
categorySlug={query?.slug as string}
/>
</div>
<Subscription />
</Container>
</div>
);
}
Category.getLayout = getLayout;
SSR for category.ts:
// This function gets called at build time
export async function getStaticPaths({ locales }: GetStaticPathsContext) {
const categories = await fetchCategories({
queryKey: [API_ENDPOINTS.CATEGORIES, { limit: 100, parent: null }],
});
const paths = categories?.data?.flatMap((category: Category) =>
locales?.map((locale) => ({ params: { slug: category.slug }, locale }))
);
return {
paths,
fallback: "blocking",
};
}
Notes:
the only changes were made before the error occured via the webGUI (deleted products).
i deleted all locales on configured one locale. Maybe theres an issue. But after these changes the build ran fine for a week.
when i run the same code on my local computer with the same node etc. Versions it works. Is there any cache that must be deleted to make it work again?
Thank you in advance for any tip that could cause this. I tried alot of things but cant figure it out yet.

Sometimes when I update the snapshots I got an Attribute __ngContext__

Sometimes when I update the snapshots I got an Attribute ngContext and for fix this problem I've to clean and install my node_modules to "fix" this issue.
I've to do this every time that I need to update a snapshot. I've already searched on multiple solutions and nothing worked.
snapshotSerializers: \[
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
\],
Can someone help me with this, please?
Here is an image
I've updated the jest versions and also the jest-present-angular too but didn't work.
I just want to have a solution that does not makes me clean install the node_modules every time
This is indeed annoying especially because it tends to change after upgrading angular version. My snapshots are now failing as well because of this difference :-/.
- __ngContext__={[Function LRootView]}
+ __ngContext__="0"
So, having look at the jest configuration, the snapshot serializers are being loaded from 'jest-preset-angular' module.
The relevant plugin here is 'jest-preset-angular/build/serializers/ng-snapshot'. Now, they are two ways what to do to get rid of __ngContext__.
replace the plugin entirely by a modified copy
Create a copy of that file in the same directory and adapt it accordingly (line https://github.com/thymikee/jest-preset-angular/blob/40b769b8eba0b82913827793b6d9fe06d41808d9/src/serializers/ng-snapshot.ts#L69):
const attributes = Object.keys(componentInstance).filter(key => key !== '__ngContext__');
Adapt the configuration:
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'./custom-snapshot-serializer.ts',
'jest-preset-angular/build/serializers/html-comment',
],
The disadvantage of this solution is that you have to maintain the plugin although only one line has been changed.
replace the plugin by a wrapper (preferred solution)
This creates just a wrapper for the original implementation. The idea is to remove __ngContext__ before it moves on down the plugin chain. However, the logic of the original plugin is used for the fixture serialization.
import type { ComponentRef, DebugNode, Type, ɵCssSelectorList } from '#angular/core';
import type { ComponentFixture } from '#angular/core/testing';
import type { Colors } from 'pretty-format';
import { test as origTest, print as origPrint } from 'jest-preset-angular/build/serializers/ng-snapshot';
/**
* The follow interfaces are customized heavily inspired by #angular/core/core.d.ts
*/
interface ComponentDef {
selectors: ɵCssSelectorList;
}
interface IvyComponentType extends Type<unknown> {
ɵcmp: ComponentDef;
}
interface NgComponentRef extends ComponentRef<unknown> {
componentType: IvyComponentType;
_elDef: any; // eslint-disable-line #typescript-eslint/no-explicit-any
_view: any; // eslint-disable-line #typescript-eslint/no-explicit-any
}
interface NgComponentFixture extends ComponentFixture<unknown> {
componentRef: NgComponentRef;
// eslint-disable-next-line #typescript-eslint/no-explicit-any
componentInstance: Record<string, any>;
}
/**
* The following types haven't been exported by jest so temporarily we copy typings from 'pretty-format'
*/
interface PluginOptions {
edgeSpacing: string;
min: boolean;
spacing: string;
}
type Indent = (indentSpaces: string) => string;
type Printer = (elementToSerialize: unknown) => string;
export const print = (fixture: any, print: Printer, indent: Indent, opts: PluginOptions, colors: Colors): any => {
const componentInstance = (fixture as NgComponentFixture).componentInstance;
const instance = { ...componentInstance };
delete instance.__ngContext__;
const modifiedFixture = { ...fixture, componentInstance: { ...instance } };
return origPrint(modifiedFixture, print, indent, opts, colors);
};
// eslint-disable-next-line #typescript-eslint/no-explicit-any, #typescript-eslint/explicit-module-boundary-types
export const test = (val: any): boolean => {
return origTest(val);
};
The configuration is adapted the same way as before.

How to implement useContext (React Native, Expo) to control weather unit settings?

I am trying to implement the ability to switch between imperial and metric units using the useContext() hook. So far, I have not had much success. I have read the React useContext() documentation and followed this article. This is my current JavaScript source code that currently does not function as intended:
App.js - where context provider is located
import React from 'react';
import WeatherScreen from './components/screens/WeatherScreen';
import { CurrentUnitContext } from './components/hooks/CurrentUnitContext.js';
export default App = () => {
return (
<CurrentUnitContext.Provider
value={"imperial"}
>
<WeatherScreen />
</CurrentUnitContext.Provider>
);
};
CurrentUnitContext.js - Intended for createContext()
import { createContext } from 'react';
/**
* WIP custom hook for setting current unit
*
* todo - change weather units here
* set imperial (F), metric (C), and maybe standard (K)
*/
export default CurrentUnitContext = createContext();
/**
export default CurrentUnitContext = createContext({
theCurrentUnit: "imperial",
setTheCurrentUnit: () => {},
});
*/
UnitSwitch.js - Intended to contain the component to set the units with user feedback.
import React, { useState, useEffect, useContext } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { CurrentUnitContext } from '../../hooks/CurrentUnitContext.js';
import { tailwind, fontConfig } from '../../../tailwind.js';
/**
* Unit Switcher child component. Based on switch's boolean
* value useState hook isEnabled, set useEffect hook currentUnit
* to either "imperial" or "metric".
*
* #param - switchHeader: Displays the unit switch header
* text passed from WeatherContent.js
* #param - imperialUnits: Text passed from WeatherContext.js for
* imperial unit button string.
* #param - metricUnits: Text passed from WeatherContext.js for
* metric unit button string.
*/
export default UnitSwitch = ({ imperialUnits, metricUnits, switchHeader }) => {
const [theCurrentUnitSetting, setTheCurrentUnitSetting] = useState("imperial");
return (
<View style={tailwind('bg-gray-300 border-t-2 p-3 w-64 h-48')}>
<Text style={tailwind('text-center text-22fz')}>
{switchHeader}
</Text>
<View style={tailwind('flex-1 justify-center items-center')}>
<TouchableOpacity
style={tailwind('')}
onPress={() => setTheCurrentUnitSetting("metric")}
>
<Text style={tailwind('')}>
{metricUnits}
</Text>
</TouchableOpacity>
</View>
</View>
);
};
getWeather.js - Hook designed to fetch weather
import { useState, useEffect, useContext } from 'react';
import useLocation from '../hooks/useLocation.js';
import { CurrentUnitContext } from './CurrentUnitContext.js';
/**
* #getWeather - if permission was granted in useLocation() hook,
* uses Object theLocation containing lat. and long. coordinates as
* decimal number values. Returns the currentWeather. useEffect()
* relies on the value of Object theLocation.
*
* #WEATHER_API_KEY - accessed from clientSecret directory,
* hidden for repo security and must be manually provided.
* #currentWeather - useState hook to store JSON result of
* current weather data.
* #baseWeatherUrl - initial OpenWeatherMap API access string
* #weatherUrl - Full OpenWeatherMap API access string
*/
export default getWeather = () => {
const theLocation = useLocation();
const theCurrentUnit = useContext(CurrentUnitContext);
const [currentWeather, setCurrentWeather] = useState();
useEffect(() => {
const { WEATHER_API_KEY } = require("../clientSecret/openWeather.json");
let baseWeatherUrl = 'https://api.openweathermap.org/data/2.5/weather?',
weatherUrl = "";
//console.log(theLocation); //confirm we are getting location, uncomment if needed
if (theLocation !== undefined) {
weatherUrl = `${baseWeatherUrl}lat=${theLocation.latitude}&lon=${theLocation.longitude}&units=${theCurrentUnit}&appid=${WEATHER_API_KEY}`;
console.log(weatherUrl); //uncomment if needed
const fetchWeather = async () => {
try {
const response = await fetch(weatherUrl);
const result = await response.json();
if (response.ok) {
setCurrentWeather(result);
} else {
alert(result.message);
};
} catch (error) {
console.log(error);
alert(error.message);
} finally {
console.log("async function fetchWeather() has been run."); //API rate call confirmation
};
};
//API calls must not occur more than once every minute.
fetchWeather();
};
}, [theLocation, theCurrentUnit]);
return currentWeather;
};
As shown right now, the error message that appears is:
TypeError: undefined is not an object (evaluating >'_CurrentUnitContext.CurrentUnitContext.Provider')
This error is located at:
in App (created by ExpoRoot)
in ExpoRoot (at renderApplication.js:45)
in RCTView (at View.js:34)
in View (at AppContainer.js:106)
in RCTView (at View.js:34)
in View (at AppContainer.js:132)
in AppContainer (at renderApplication.js:39)
I was assisted, in CurrentUnitContext.js, changing
export default CurrentUnitContext = createContext();
to
export let CurrentUnitContext = createContext();
fixed the error.

React Native, UI Kitten Input custom style on default and onFocus states

I need some help about creating a custom input style on default and onFocus states.
import React, {useState} from 'react';
import {
StyleSheet,
View,
} from 'react-native';
import {
Input,
Layout,
} from '#ui-kitten/components';
export const CustomInputExample = () => {
const [ focusStatus, setFocusStatus ] = useState(false)
const onMouseEnter = () => {
setFocusStatus(true)
}
const onMouseLeave = () => {
setFocusStatus(false)
}
return (
<Layout>
<Input
style={focusStatus ? styles.customStyle : styles.basicStyle}
status={focusStatus ? 'success' : 'basic'}
placeholder='Success'
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
/>
</Layout>
);
};
const styles = StyleSheet.create({
basicStyle: {
borderColor: grey,
},
customStyle: {
borderColor: '#3CB46E'
},
});
But, none of the methods are working in my case. I've tried other InputProps like focus, onTextFieldFocus, onTextFieldBlur...May be I do not know how to use them.
Also this is the error from ts =>
Property 'onMouseEnter' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<...> & Readonly<...>'.ts(2322)
Any help can be grateful.
onMouseEnter and onMouseLeave will not work unless you build a custom component and then only if you use TouchableWeb. Additionally it will only work on web (No hover events on phone or tablet).
Of course this will require writing your own mapping following UI-Kitten's Create a Custom Component Mapping directions
At last, I've found the solution. I'am writing to help others who uses react-native-ui-kitten.
InputComponent implements WebEventResponderCallbacks interface so =>
export interface WebEventResponderCallbacks {
onMouseEnter?: () => void;
onMouseLeave?: () => void;
onFocus?: () => void;
onBlur?: () => void;
}
I don't know the reason why onMouseEnter, onMouseLeave or any other methods of InputComponent have no use but onFocus and onBlur are working.
You don't need to implement these interfaces in case you follow Branding guide. You can change primary colors everywhere so your app will follow a single source of truth about styling.

Angular 2 - bypasscecurity

I habe problem with the "security" of angular 2. I try to calculate a span-witdh within a ngfor-loop:
<span style="width:updateStyle({{ ((date | amDifference : item.startdate : 'minutes' :true)/item.duration*100) | round }})% .....more span>
And import/changed a bypass-security.component from internet:
import { Component } from '#angular/core';
import { DomSanitizer, SafeStyle, SafeResourceUrl, SafeUrl } from '#angular/platform-browser';
#Component({
selector: 'bypass-security',
templateUrl: 'app/bypass-security.component.html',
})
export class BypassSecurityComponent {
dangerousUrl: string;
trustedUrl: SafeUrl;
dangerrousStyle: string;
trustedStyle: SafeStyle;
// #docregion trust-url
constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousUrl = 'javascript:alert("Hi there")';
this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
this.trustedStyle = sanitizer.bypassSecurityTrustStyle(this.dangerrousStyle);
}
updateStyle(id: string)
{
this.trustedStyle = this.sanitizer.bypassSecurityTrustStyle(this.id);
}
}
But still get this error:
WARNING: sanitizing unsafe style value width:83%; height:3px; background-color:#d9d9d4; display:inline-block; (see http://g.co/ng/security#xss).
What can I do?
Thanks!
Calling methods from view bindings is usually bad practice because this method is called every time Angular2 checks for changes (runs change detection)
I don't really get what you try to accomplish, but if you want to set the width in % do something like
<span [style.width.%]="width">
and assign the value you want to be used for width to a property with that name
constructor() {
this.width = updateStyle(((date | amDifference : item.startdate : 'minutes' :true)/item.duration*100) | round }})
// I have a really hard time figuring out what this is supposed to do
I used the constructor only for an example. do the calculation whenever you think it should be updated (some event, some lifecycle callback, ...)

Resources