"Failed to compile" error on npm run build - reactjs

I am trying to deploy a react JS app and am stuck at npm run build. My command line is throwing this error when I attempt to compile my react js (typescript) project with npm run build command:
Type error: Argument of type 'firebase.default.auth.Auth' is not assignable to parameter of type 'import("/Users/jaxfloyd/Documents/Programming/The_Sportsbook/get-rich-or-die-trying/growth/next-firebase-stripe/node_modules/#firebase/auth/dist/auth-public").Auth'
The CLI points to my index.tsx file as the problem:
7 |
8 | export default function Home() {
9 | const [user, userLoading] = useAuthState(firebase.auth());
| ^
10 | console.log("User is:", user);
11 |
12 | return (
This is my full index.tsx file:
import React from "react";
import Login from "../components/Login";
import styles from "../styles/Home.module.css";
import firebase from "../firebase/firebaseClient";
import { useAuthState } from "react-firebase-hooks/auth";
import { createCheckoutSession } from "../stripe/createCheckoutSession";
export default function Home() {
const [user, userLoading] = useAuthState(firebase.auth());
console.log("User is:", user);
return (
<div className={styles.container}>
{!user && userLoading && <h1>Loading...</h1>}
{!user && !userLoading && <Login />}
{user && !userLoading && (
<div>
<h1>Hello, {user.displayName}</h1>
<button onClick={() => createCheckoutSession(user.uid)}>
Upgrade to premium!
</button>
</div>
)}
</div>
);
}
Nothing online has an alternate import statement I can use for useAuthState. Any help would be much appreciated.

There are two versions of Firebase, you are using them together instead of just one. Use Firebase version 8 or 9 not both of them. If library "react-firebase-hooks/auth" is using functional approach, use Firebase version 9 to get Auth. You need to use function import { getAuth } from 'firebase/auth'. Same i dont know how you initialize app in version 9 you can do it using function import { initializeApp } from 'firebase/app'.

Related

Error when navigating to `/blog` in next.js project

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

how to mock a function that is redirecting to a route using enzyme?

I have a function being called on onClick of a button. The function redirects to a URL to another component. I am facing problems while writing a unit test for it.
Here is my button and the onClick function:
import { useHistory } from "react-router-dom";
export default function ABC() {
const history=useHistory();
const handleCreateClick=()=>{
history.push("/servicecatalog/create");
};
return (
<>
<div cds-layout="vertical gap: md p:lg">
<h1>
HEADER_TEXT
</h1>
<p>SUBTEXT</p>
<button onClick={handleCreateClick}>CREATE_BTN</button>
</div>
</>
);
}
I want to write unit test to test the redirect path the button is redirecting to. here is what I tried:
import { mount} from "enzyme";
import React from "react";
import ABC from "./ABC";
import { useHistory } from "react-router-dom";
describe( ABC, ()=>{
it("renders ABC with proper text.", ()=>{
const wrapper = mount(<ABC />);
const history=useHistory();
const mockFn=jest.fn(()=>history.push("/servicecatalog/create"));
expect(wrapper.find("div")).toBeTruthy();
expect(wrapper.find("h1").text()).toEqual(HEADER_TEXT);
expect(wrapper.find("p").text()).toEqual(SUBTEXT);
expect(wrapper.find("button").text()).toEqual(CREATE_BTN);
wrapper.find("button").simulate("click");
expect(mockFn).toBeCalled();
});
});
With this UT, I get the following 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
I also tired with just const mockFn=jest.fn();
But then I got this error:
TypeError: Cannot read property 'push' of undefined
12 | const history=useHistory();
13 | const handleCreateClick=()=>{
> 14 | history.push("/servicecatalog/create");
| ^
15 | };
16 | return (
17 | <>
Anyone who can point out my mistake?

While using redux in react, the moment I use <Provider></Provider> in my code it throws weird error. what's this?

I'm creating an app using react js, using react-redux as state manager. I have created a file to store all my states at one place and while using the Provider in my app.js I'm getting this weird huge error. I'm a beginner and learning redux and in the beginning I am not able to understand this. Please help someone as soon as possible.
my app.js looks like this:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Contacts from './components/contacts/Contacts';
import AddContact from './components/contacts/AddContact';
import EditContact from './components/contacts/EditContact';
import Header from './components/layout/Header';
import About from './components/pages/About';
import NotFound from './components/pages/NotFound';
import {Provider} from 'react-redux';
import store from './store';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className="App">
<Header branding="Contact Manager" />
<div className="container">
<Switch>
<Route exact path="/" component={Contacts} />
<Route exact path="/contact/add" component={AddContact} />
<Route exact path="/contact/edit/:id" component={EditContact} />
<Route exact path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</div>
</div>
</Router>
</Provider>
);
}
}
export default App;
if I don't use Provider here, app runs. Screenshot of errors is attached.
The errors I get:
Provider
C:/Users/lenovo/Desktop/contactmanager_redux/node_modules/react-redux/es/components/Provider.js:11
8 | var store = _ref.store,
9 | context = _ref.context,
10 | children = _ref.children;
> 11 | var contextValue = useMemo(function () {
12 | var subscription = createSubscription(store);
13 | subscription.onStateChange = subscription.notifyNestedSubs;
14 | return {
View compiled
mountIndeterminateComponent
C:/Users/lenovo/Desktop/contactmanager_redux/node_modules/react-dom/cjs/react-dom.development.js:13380
13377 | }
13378 |
13379 | ReactCurrentOwner.current = workInProgress;
> 13380 | value = fn(props, context);
13381 | }
13382 | // React DevTools reads this flag.
13383 | workInProgress.effectTag |= PerformedWork;
View compiled
beginWork
C:/Users/lenovo/Desktop/contactmanager_redux/node_modules/react-dom/cjs/react-dom.development.js:13820
13817 |
13818 | switch (workInProgress.tag) {
13819 | case IndeterminateComponent:
> 13820 | return mountIndeterminateComponent(current, workInProgress, renderExpirationTime);
13821 | case FunctionalComponent:
13822 | return updateFunctionalComponent(current, workInProgress);
13823 | case ClassComponent:
Here is the screenshot of errors:
Here is the code in my store.js :
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const initialState = {};
const middleware = [thunk];
const store = createStore(rootReducer, initialState, compose(applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()));
export default store;
following is the code in the rootReducer from './reducers/index' :
import {combineReducers} from 'redux';
import contactReducer from './contactReducer';
const rootReducer = combineReducers({
contact: contactReducer
});
export default rootReducer;
and contactReducer from './contactReducer':
const initialState = {};
export default function(state = initialState, action){
switch(action.type){
default:
return state;
}
}
The issue happens because of your version. Not all versions are compatable with eatch other and it seems your react and react-dom is not compatable with react-redux. You need to update it. Type this into your terminal in your project root
npm upgrade react react-dom
This should update your packages and work fine after a restart.
In addition, I took a look at your project and here is few quick TIPs:
1st. .js is for javascript. If you are returning html (for example your APP.js file) it should end in .jsx. The jsx means javascript xml. While it works... thats not how it suppost to be. Any file with a return of HTML should be .jsx or .tsx for typescript.
2nd. DONT put node_modules folder in your repository. Its a folder where your packages are stored. You dont need it. The package.json keeps track of what packages you need of what version. Whenever you freshly pull a project simply do npm i (short for npm install) and all the packages will be downloaded for you.
3nd. Dont put package-lock.json. Its uneeded. It get generated whenever yo urun npm i to install nay package.
4th. Nowadays a standart is ES6. Meaning all the classes you have - would recommend switching to arrow functions. Instead of
class App extends Component {
render() {
..code..
}
}
it would be
const App = () => {
return {
..code..
}
}
When working with states and lots of logic, arrow functions are cleaner IMO.
5th. clean code! There are guides on this on a basic scale. There is a hard limit of how many characters you should have in a single line - break up your code. There are rules of when you should break your code and in what section. This all matters. While the code works - not correctly formatted code can be hard to read and debug. If your using a visual studio code (VSC) I woudl recommend an extension Prettier - code formatter. Its a life savior!
In addition dont do
if (name === "") {
this.setState({ errors: { name: "Name is required" } });
return;
}
if (email === "") {
this.setState({ errors: { email: "Email is required" } });
return;
}
if (phone === "") {
this.setState({ errors: { phone: "Phone is required" } });
return;
}
If you need so many IFs then use switch. But in your case you can simply do a single function to check if its empty or not and a loop to check each field that is required. Or better yet - use build in required tag on form elements. You can give required parameter to <input /> to make it required on form submit. and make a custom error message for it. There are many ways to handle it and yours is not the way. Would suggest looking more into it :)
Hope these short tips help and the update help your issue :)

Jest - Cannot use import statement outside a module - using Rescript

I am trying to run unit tests in a React project generated using react-scripts, in which I added ReScript support.
When I run the tests, however, I encountered an error in the transpiled javascript code.
Details of the error:
/Users/massimilianodacunzo/Projects/Elixir/test-project/apps/phoenix_react_web/assets/node_modules/bs-platform/lib/es6/array.js:3
import * as Curry from "./curry.js";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 |
2 |
> 3 | import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
| ^
4 | import * as React from "react";
5 |
6 | function TestComponent(Props) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/components/users/TestComponent.bs.js:3:1)
The components I am trying to test:
App.res
%%raw(`
import logo from './logo.svg';
import './App.css';
`)
#react.component
let make = () => {
<div className="App">
<TestComponent elements={["1", "2", "3"]} />
</div>
}
TempComponent.res
#react.component
let make = (
~elements: array<string>
) => {
<ul>
{
React.array(
elements
|> Array.map(e =>
<li key={e}>{React.string(e)}</li>)
)
}
</ul>
}
The generated TestComponent.bs.js
import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
import * as React from "react";
function TestComponent(Props) {
var elements = Props.elements;
return React.createElement("ul", undefined, $$Array.map((function (e) {
return React.createElement("li", {
key: e
}, e);
}), elements));
}
var make = TestComponent;
export {
make ,
}
/* react Not a pure module */
Is there any additional configuration I can add to the react-scripts test script?
Following the comment of glennsl, I followed the git issue, discovering that the configuration in my bsconfig.json file specified the package-specs module as es6. The test error didn't appear if I change the configuration to commonjs.
{
...
"package-specs": {
"module": "commonjs",
"in-source": true
}
...
}
Again, thanks to glennsl for pointing me in the right direction.

TypeError: Object(...) is not a function when using react-toastify

I'm trying to get react-toastify to work in an app I'm writing while following an online course. I'm supposed to install a specific version but I always prefer using the very latest one but when I do, I'm getting a bunch of errors.
I've gone to the npm home page for React-Toastify and they provide very good documentation on how to use it and I believe I've followed the instructions from both the course and react-toastify correctly but I'm still getting an error.
I've defined react-toastify as the top of my App.js
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
and I'm simply calling a test toast as follows:
handleDelete = (post) => {
toast("deleted");
// toast.error("deleted");
}
and in my render method I have the <ToastContainer />:
render() {
return (
<React.Fragment>
<ToastContainer />
<button className="btn btn-error" onClick={this.handleDelete}>
Delete
</button>
When I click on my delete button I get an error (well I'm actually getting a bunch of them but this is the main one):
TypeError: Object(...) is not a function
useToastContainer
..myapp/node_modules/react-toastify/dist/react-toastify.esm.js:866
863 | }
864 |
865 | function useToastContainer(props) {
> 866 | var _useReducer = useReducer(function (x) {
867 | return x + 1;
868 | }, 0),
869 | forceUpdate = _useReducer[1];
Actually, I've just noticed that my <ToastContainer /> was commented out in my render method and the second I uncomment it, the same error occurs immediately as my page loads.
Am I missing something or is this a bug with react-notify and the version of React I'm using i.e. 16.4.1?
I was also facing a similar issue, this is because there are some conflicting dependencies with react-toastify in the newer versions with respect to its predecessor.
Also if you follow some courses they usually provide some resources to proceed with, when you start working on those resource and do a npm i for its dependencies it install certain versions of the package which is specified in the package.json file, so if you are trying to install a new package as a part of the course it might not be compatible with the ones mentioned in the resource files.
So to avoid conflict here you can manually install all the packages mentioned in package.json with the latest versions then install the latest version of react-toastify
OR
Try reverting the version of react-toastify to earlier version , maybe try with react-toastify#4.1 or the version mentioned in the course. (This worked for me)
install an older version of react-toastify and it will work just fine
Remove unused props.
handleDelete = () => {
toast("deleted");
// toast.error("deleted");
}
Or use the function props.
handleDelete = (post) => {
toast(post);
}
And call your function in arrow function.
render() {
return (
<React.Fragment>
<ToastContainer />
<button className="btn btn-error" onClick={() => {this.handleDelete('deleted')}}>
Delete
</button>
</React.Fragment>
)
What works for me was to create another file to hold the <ToastContainer/> and then import it in my App.js and it works fine. Here I'm giving you a simple example:
./src/toast.jsx
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const Toast = () => {
const errorMessage = () => {
toast.error("Unexpected error occured");
};
return (
<div>
<button onClick={errorMessage} className="btn btn-primary">
Submit
</button>
<ToastContainer />
</div>
);
};
export default Toast;
./src/App.js
import React, { Component } from "react";
import "./App.css";
import Toast from "./toast";
class App extends Component {
state = {
};
render() {
return (
<React.Fragment>
//Your code...
<Toast />
</React.Fragment>
);
}
}
export default App;
However, my application is a little bit more complex and basically I have a file httpServices.js, where I'm using Axios library to make HTTP requests and catch errors. So if I catch an error while sending an Http request and I'm using "toast.error("Message")". I'm using the new file toast.jsx to hold a container for the errors and this container I import in my App.js.

Resources