React invalid hook call error with functional component - javascript

here is my code :
import * as React from 'react';
import { ReactReduxContext } from 'react-redux';
import { getDiagramId } from '#app/wireframes/model';
const HOC = () => {
const storeContext = React.useContext(ReactReduxContext);
const diagram = () => {
const selectedDiagramId = getDiagramId(storeContext.store.getState());
console.log(selectedDiagramId);
};
return (diagram);
};
export default HOC;
ERROR:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component
I get the same error no matter what I did, what could be the reason and solution?

Related

In run "#mdx-js/mdx" Uncaught (in promise) SyntaxError: Unexpected identifier 'Promise' error

import { run } from "#mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
const mdxToJsx = async (value) => {
const { default: Content } = await run(value, runtime);
return Content
};
export default mdxToJsx;
Here as per mdx library, I want to convert mdx to jsx but I got Uncaught (in promise) SyntaxError: Unexpected identifier 'Promise'
at new AsyncFunction ()
at run (run.js:15:1)
Kindly help me. Thanks Happy coding.
import React, { Fragment, useEffect, useState } from "react";
import { run } from "#mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
export default function MdxToJsx({code}) {
const [mdxModule, setMdxModule] = useState()
const Content = mdxModule ? mdxModule.default : Fragment
useEffect(() => {
(async () => {
setMdxModule(await run(code, runtime))
})()
}, [code])
return <Content />
}
I tried this one also but got the same error.

React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component

Can anyone help me with React Hooks basics, I am relatively new and couldn't find proper help online
import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"
const GoogleAuth = async() => {
const navigate = useNavigate()
auth.signInWithPopup(provider).then(() => {
navigate('/home');
}).catch((error) => {
console.log(error.message)
})
}
export default GoogleAuth
I get error on const navigate = useNavigate() saying:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component
What they want for useNavigate (and all hooks) is to be called only at the top level of a React component or a custom hook.
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.
See Rules of Hooks for more.
A solution to your problem could be calling const navigate = useNavigate() in the component where you will use GoogleAuth, and pass navigate as parameter.
As an example like so:
import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"
const GoogleAuth = async(navigate) => {
auth.signInWithPopup(provider).then(() => {
navigate('/home');
}).catch((error) => {
console.log(error.message)
})
}
export default GoogleAuth
import GoogleAuth from "GoogleAuth";
const App = ()=>{
/*
here at the top level, not inside an if block,
not inside a function defined here in the component...
*/
const navigate = useNavigate();
useEffect(()=>{
GoogleAuth(navigate)
},[])
return <div></div>
}
export default App;

Enzime: Wait that context is updated to start execute tests

I have a React app that I need to test. It's using the useContext() hook to create Provider that are using in most of my components. I have a dedicated component to handle a Context (lets say UserContext for the example) that look like that:
UserContext.jsx:
import React from 'react'
export const UserContext = React.createContext(undefined)
export const UserProvider = (props) => {
const [currentUser, setCurrentUser] = React.useState(undefined)
const context = {
currentUser,
setCurrentUser,
}
return (
<UserContext.Provider value={context}>
{props.children}
</UserContext.Provider>
)
}
So you can use the Provider like that:
import { UserProvider } from './context/UserContext'
<UserProvider>
{ ... }
</UserProvider>
Now I need to test a component that use this UserContext so let's say UserModal:
UserModal.test.jsx
import React from 'react'
import { mount } from 'enzyme'
import { BrowserRouter as Router } from 'react-router-dom'
import { UserProvider, UserContext } from '../context/UserContext'
import UserModal from '../components/UserModal'
// D A T A
import exampleUser from '../data/user.json' // Load user's data from a json file
describe('<UserModal />', () => {
let wrapper
const Wrapper = () => {
const { setCurrentUser } = React.useContext(UserContext)
React.useEffect(() => {
// Init UserContext value
setCurrentUser(exampleUser)
}, [])
return (
<UserProvider>
<UserModal />
</UserProvider>
)
}
beforeEach(() => {
wrapper = mount(<Wrapper />)
})
})
Problem is that when <UserModal /> is mounted inside of the <UserProvider>, I get an error that the currentUser in the UserContext is undefined. This error make sense because I call setCurrentUser() when the component is mounted once using React.useEffect(() => { }, []).
So have you an idea how I can mount() my <UserModal /> component inside of a context's provider in the way that the context is not undefined?
Your test should look like this:
import React from 'react'
import { mount } from 'enzyme'
import { BrowserRouter as Router } from 'react-router-dom'
import { UserProvider, UserContext } from '../context/UserContext'
import UserModal from '../components/UserModal'
// D A T A
import exampleUser from '../data/user.json' // Load user's data from a json file
describe('<UserModal />', () => {
let wrapper
const Wrapper = () => {
const { setCurrentUser } = React.useContext(UserContext)
React.useEffect(() => {
// Init UserContext value
setCurrentUser(exampleUser)
}, [])
return (
<UserModal />
)
}
beforeEach(() => {
wrapper = mount(<UserProvider><Wrapper /></UserProvider>)
})
})
Or see codesandbox here - simple test passes.
Note that UserProvider wraps Wrapper and not is used inside. It's like this because if you are using it inside, there is no UserContext to get with useContext hook, therefore there is no setCurrentUser function.

error when trying to fetch data from server Parsing error: Unexpected token

I am working with pern stack and when I try using useEffect or useState, I am getting this error.
so, I used postgres to create database and used express to connect using pool
created a endpoint and tried fetching that in my code
import React, {useEffect , useState} from 'react';
import Table from './Table';
import Nav from './Navi';
import TemplateList from './TemplateList';
import {Tab,Tabs} from 'react-bootstrap';
class Dashboard extends React.Component{
const [tdata,setTdata] = React.useState([]);
info = async () => {
try {
const response = await fetch("http://localhost:8080/dashboard");
const dataServer = await response.json();
React.setTdata(dataServer);
} catch (err) {
console.error(err.message);
}
}
console.log(tdata);
React.useEffect(() => {
info();
}, []);
error
Failed to compile
./src/components/Dashboard.js
Line 7:9: Parsing error: Unexpected token
5 | import {Tab,Tabs} from 'react-bootstrap';
6 | class Dashboard extends React.Component{
> 7 | const [tdata,setTdata] = React.useState([]);
| ^
8 |
9 | info = async () => {
10 | try {
You can't use React hooks in a Class-Based component, change your class into a pure functional component like this:
import React, { useEffect, useState } from "react";
import Table from "./Table";
import Nav from "./Navi";
import TemplateList from "./TemplateList";
import { Tab, Tabs } from "react-bootstrap";
const Dashboard = (props) => {
const [tdata, setTdata] = useState([]);
const info = async () => {
try {
const response = await fetch("http://localhost:8080/dashboard");
const dataServer = await response.json();
setTdata(dataServer);
} catch (err) {
console.error(err.message);
}
};
console.log(tdata);
useEffect(() => {
info();
}, []);
return {
<div>
/* your JSX here */
</div>
};
};
More about hooks here: https://reactjs.org/docs/hooks-intro.html

React Jest Test Failing - type.toUpperCase is not a function

I'm trying to write tests using Jest for React. However, I'm getting the following error:
TypeError: type.toUpperCase is not a function
React (images.js):
import React, { Component } from 'react';
export class Images extends Component {
render() {
return (
<div class="images">
</div>
);
}
}
Test (Jest):
jest.autoMockOff();
import React from 'react';
import TestUtils from 'react-addons-test-utils';
const ImagesComponent = require('../src/Components/images');
describe('ImagesComponent', () => {
it('Render instance of div class=images in DOM', () => {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<ImagesComponent className="images" />);
imagesDivComponent = shallowRenderer.getRenderOutput();
expect(imagesDivComponent.props.className).toEqual('images');
});
});
Redefine your React component from:
export class Images extends Component {...}
to:
var Images = React.createClass ({...)};
module.exports = Images;

Categories

Resources