redux-form is not showing its all props values - javascript

i want to use all eventHandler of redux-form as show in sameple output image but its not coming as a props so i facing undefine error now what i can do to solve the issue
i have imported reducers in index.js file of src folder and create store
package.json
{
"name": "reactjs",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^4.11.0",
"#material-ui/icons": "^4.9.1",
"prop-types": "^15.7.2",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.2.0",
"react-transition-group": "^4.4.1",
"redux-form": "^8.3.6"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
}
reducers/index.js
import { reducer } from 'redux-form';
import { combineReducers } from "redux";
export default combineReducers({
reducer
})
TouristRegistration.js
import React, { Component } from 'react';
import { reduxForm, Field } from "redux-form";
import { Button } from "#material-ui/core"
import RegistrationField from "./ReaperComponent"
class TutiorsRegistrationForm extends Component {
handlenextpage = () => {
this.props.nextPage()
}
render() {
return (
<form>
<Field
type="text"
name="FirstName"
component={RegistrationField}
/>
<Button
color="primary"
variant="contained"
type="submit"
>Next
</Button>
</form>
);
}
}
const validate = (value) => {
const errors = {}
if (!value.FirstName) {
errors.FirstName = "Required"
}
console.log("error " + JSON.stringify(errors));
return errors;
}
export default reduxForm({
validate: validate,
form: 'TutiorsRegistrationForm'
})(TutiorsRegistrationForm);
RegistrationField.js
import React from 'react';
import { TextField } from "#material-ui/core"
const ReaperComponent = (props) => {
console.log("props " + JSON.stringify(props));
return (
<TextField />
);
}
export default ReaperComponent;
output
of instructor
output in my case
props {"input":{"name":"FirstName","value":""},"meta":{"active":false,"asyncValidating":false,"autofilled":false,"dirty":false,"form":"TutiorsRegistrationForm","invalid":false,"pristine":true,"submitting":false,"submitFailed":false,"touched":false,"valid":true,"visited":false}}

Related

Tailwindcss does not get loaded in react application

I am using the following packages and have installed tailwindcss in the following project folder /home/admin/Desktop/Code/main_project/client/package.json:
{
"name": "react-app",
"version": "1.0",
"private": true,
"dependencies": {
"babel-eslint": "10.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router": "^6.3.0",
"react-scripts": "3.2.0",
"redux": "^4.1.1",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.0.1",
"web3": "^1.6.1",
"web3-eth-contract": "^1.5.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"tailwindcss": "^3.0.24"
}
}
My tailwind.config.js looks like the following:
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
As you can see my react-project lies in a subfolder.
My postcss.config.js looks like the following:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
This is my index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
In my index.js I am loading my index.css:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from "./redux/store";
import { Provider } from "react-redux";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
My App.js looks like the following:
import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "./redux/blockchain/blockchainActions";
import { fetchData } from "./redux/data/dataActions";
import "./App.css";
function App() {
const dispatch = useDispatch();
const blockchain = useSelector((state) => state.blockchain);
const data = useSelector((state) => state.data);
const [CONFIG, SET_CONFIG] = useState({
CONTRACT_ADDRESS: "",
SCAN_LINK: "",
NETWORK: {
NAME: "",
SYMBOL: "",
ID: 0,
},
NFT_NAME: "",
SYMBOL: "",
MAX_SUPPLY: 1,
WEI_COST: 0,
DISPLAY_COST: 0,
GAS_LIMIT: 0,
MARKETPLACE: "",
MARKETPLACE_LINK: "",
SHOW_BACKGROUND: false,
});
const getData = () => {
if (blockchain.account !== "" && blockchain.smartContract !== null) {
dispatch(fetchData(blockchain.account));
}
};
const getConfig = async () => {
const configResponse = await fetch("/config/config.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const config = await configResponse.json();
SET_CONFIG(config);
};
useEffect(() => {
getConfig();
}, []);
useEffect(() => {
getData();
}, [blockchain.account]);
return (
<>
<h1 className="text-3xl font-bold underline">Welcome</h1>
<>
);
}
export default App;
However, the components in my App.js do not get rendered with tailwindcss.
Any suggestions what I am doing wrong?
I appreciate your replies!

(...).mockImplementation is not a function

I've used this test in the past with a React app without any issues:
import { render, fireEvent, screen, waitFor } from '#testing-library/react'
import { RelatedContent } from '../components/relatedcontent'
import { onValue } from '../components/firebase'
jest.mock('../components/firebase')
test('RelatedContent -> displays related content', async () => {
let fakeData = {
'flex-new-row': 20,
'chronlabs': 25
}
let snapshot = {val: () => fakeData}
onValue.mockImplementation((ref, callback) => {
callback(snapshot)
return jest.fn()
})
render(<RelatedContent numRelated = {5}/>)
await waitFor(() => expect(document.querySelector("a[href='/flex-new-row']")).toBeTruthy())
await waitFor(() => expect(document.querySelector("a[href='/chronlabs']")).toBeTruthy())
})
Now I'm using the same test on a Next.js app, and I'm getting the following error:
TypeError: _firebase.onValue.mockImplementation is not a function
Update
The RelatedContent component looks like:
import React, { useState, useEffect } from 'react'
import { db, onValue, ref } from './firebase'
const RelatedContent = ({ numRelated }) => {
const [related, setRelated] = useState([])
useEffect(() => {
let unsubscribe = onValue(ref(db, `posts/related`), snapshot => {
let _related = Object.keys(snapshot.val())
setRelated(_related)
})
return () => unsubscribe()
}, [])
return(
<div className = 'Related'>
{related.slice(0, numRelated).map((elem, i) =>
<Link href = {elem}>Whatever</Link>
)}
</div>
)
}
export default RelatedContent
And the Firebase component looks like:
import { initializeApp } from 'firebase/app'
import { getDatabase, goOnline, goOffline, limitToLast, onDisconnect, onValue, orderByValue, push, query, ref, remove, runTransaction, update } from 'firebase/database'
const config = { ... }
const app = initializeApp(config)
const db = getDatabase(app)
export { db, dbt, goOnline, goOffline, limitToLast, onDisconnect, onValue, orderByValue, push, query, ref, remove, runTransaction, update }
package.json looks like:
{
"name": "app-next",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest"
},
"dependencies": {
"#primer/octicons-react": "^16.3.0",
"chart.js": "^2.7.2",
"firebase": "^9.6.4",
"gfm": "0.0.1",
"moment": "^2.29.1",
"next": "12.0.8",
"prismjs": "^1.26.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-markdown": "^8.0.0",
"rehype-katex": "^6.0.2",
"rehype-raw": "^6.1.1",
"remark-gfm": "^3.0.1",
"remark-math": "^5.1.1"
},
"devDependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"eslint": "8.7.0",
"eslint-config-next": "12.0.8",
"eslint-plugin-promise": "^6.0.0",
"jest": "^27.4.7"
}
}
If I place the fake data and the onValue.mockImplementation() function before the test declaration, the test passes correctly.
The problem is that I've several tests with multiple definitions of the fake data, and I need to declare the fake data within every test.
If I do so, I get the error.

TypeError: [setState with createContext] is not a function - React

I am using React's Context API to call setCurrentUser below. But it gives me this error:
TypeError: setCurrentUser is not a function.
Upon logging console.log(useContext(globalContext)), I get the empty object {}.
I have manually converted my project from TS(where it worked by specifying setCurrentUser as type Dispatch) to JS, so I am not sure if that broke something...at least my react and react-dom packages should be current.
How do we make this work with JS? Thanks
Router.jsx - where I am calling setCurrentUser
import React, { useContext, useEffect } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import LoginPg from "../pages/LoginPg/LoginPg";
import ErrorHandler from "./ErrorHandler";
import ErrorPg from "../pages/ErrorPg/ErrorPg";
import useGet from "../../server_api/useGet";
import ProtectedRoute from "./ProtectedRoute";
import HomePg from "../pages/HomePg/HomePg";
import { globalContext } from "../../store/context/globalContext";
import CalendarPg from "../pages/Calendar/CalendarPg";
function Router() {
const { currentUser, setCurrentUser } = useContext(globalContext);
const [doGet] = useGet();
let user;
console.log(useContext(globalContext)); // <==== logs: {}
useEffect(() => {
doGet("auth/authenticate", (res) => {
if (res) {
user = res.username;
setCurrentUser(res);
} else {
console.log("Router: user not authenticated");
}
});
}, []);
return (
<BrowserRouter>
<ErrorHandler>
<Switch>
<Route path="/error" component={ErrorPg} />
<Route path="/login" component={LoginPg} />
<ProtectedRoute
path="/calendar"
Component={CalendarPg}
isAuth={currentUser}
key="uniquevalue"
/>
<ProtectedRoute path="/" Component={HomePg} isAuth={currentUser} />
</Switch>
</ErrorHandler>
</BrowserRouter>
);
}
export default Router;
globalContext.jsx
import { createContext, useState } from "react";
export const globalContext = createContext({});
export default function GlobalContext(props) {
const [currentUser, setCurrentUser] = useState(null);
return (
<globalContext.Provider value={{ currentUser, setCurrentUser }}>
{props.children}
</globalContext.Provider>
);
}
package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"homepage": "/",
"dependencies": {
"#fullcalendar/daygrid": "^5.9.0",
"#fullcalendar/interaction": "^5.9.0",
"#fullcalendar/react": "^5.9.0",
"#fullcalendar/timegrid": "^5.9.0",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"antd": "^4.16.13",
"axios": "^0.21.1",
"bootstrap": "^5.1.1",
"font-awesome": "^4.7.0",
"fullcalendar": "^5.9.0",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"query-string": "^4.3.4",
"react": "^17.0.2",
"react-calendar": "^3.4.0",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-modal": "^3.14.3",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"sass": "^1.39.2",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"cypress": "npx cypress open"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"cypress": "^7.5.0"
}
}
You need the consumer (Router) to be a child of the provider (GlobalContext).
Also your component names should start with an Upper case.
import { GlobalContext } from "../../store/context/GlobalContext";
const App = () => {
const [currentUser, setCurrentUser] = useState(DEFAULT_USER);
return (
<GlobalContext.Provider value={{ currentUser, setCurrentUser }}>
<Router />
</GlobalContext.Provider>
);
};

Redux action creator getting "TypeError: dispatch(...) is not a function" (code attached)?

Any ideas why I am getting the following this "dispatch is not a function" error in my listEventsActionCreator function when it calls "dispatch(listEventsRequestedAction())" ???
If I comment out the lines in this method after the dispatch it actually then works which is strange.
Using react-create-app, with redux, typescript, thunk.
ERROR:
TypeError: dispatch(...) is not a function
CODE:
export function listEventsRequestedAction() {
return {
type: PlannerEventTypes.LIST_EVENTS_REQUESTED
}
}
export const listEventsReceivedAction = (events:PlannerEvent[]) => {
return {
type: PlannerEventTypes.LIST_EVENTS_RECEIVED,
events
}
}
export const listEventsErrorAction = (err:any) => {
return {
type: PlannerEventTypes.LIST_EVENTS_ERROR,
error: err
}
}
export const listEventsActionCreator = () => {
return (dispatch: any) => {
dispatch(listEventsRequestedAction()) // <== ERROR: TypeError: dispatch(...) is not a function
(API.graphql(graphqlOperation(listEvents)) as Promise<any>).then((results:any) => {
const events = results.data.listEvents.items
dispatch(listEventsReceivedAction(events))
}).catch((err:any) => {
// console.log("ERROR")
dispatch(listEventsErrorAction(err))
})
}
}
package.json
{
"name": "planner",
"version": "0.1.0",
"private": true,
"dependencies": {
"#types/graphql": "^14.0.7",
"#types/react-redux": "^6.0.10",
"aws-amplify": "^1.1.19",
"aws-amplify-react": "^2.3.0",
"date-fns": "^1.30.1",
"eslint": "^5.9.0",
"konva": "^2.5.1",
"moment": "^2.22.2",
"moment-timezone": "^0.5.23",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-draggable": "^3.0.5",
"react-konva": "^16.6.31",
"react-moment": "^0.8.4",
"react-redux": "^5.1.1",
"react-scripts-ts": "3.1.0",
"redux": "^4.0.1",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts-ts start",
"build": "react-scripts-ts build",
"test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject"
},
"devDependencies": {
"#types/jest": "^23.3.10",
"#types/node": "^10.12.10",
"#types/react": "^16.7.10",
"#types/react-dom": "^16.0.11",
"#types/redux-logger": "^3.0.7",
"typescript": "^3.2.1"
}
}
index.tsx
import * as React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { applyMiddleware, createStore } from 'redux'
import App from './App'
import './index.css'
import rootReducer from './reducers/index'
import registerServiceWorker from './registerServiceWorker'
import { createLogger } from 'redux-logger'
import thunkMiddleware from 'redux-thunk'
const loggerMiddleware = createLogger()
const store = createStore (
rootReducer,
applyMiddleware(
thunkMiddleware, // lets us dispatch() functions
loggerMiddleware // neat middleware that logs actions
)
)
render(
<Provider store={store}>
<App testStr='test' />
</Provider>
,document.getElementById('root') as HTMLElement
);
registerServiceWorker();
The problem is because of the syntax that you followed. You don't have a semicolon after dispatch(listEventsRequestedAction()) and since you follow it up with (API.graphql(graphqlOperation(listEvents) as Promise<any>) while compiling it is evaluted as dispatch(listEventsRequestedAction())(API.graphql(graphqlOperation(listEvents) as Promise<any>) and hence it gives you the error.
Adding a semicolon after dispatch(listEventsRequestedAction()) would work
export const listEventsActionCreator = () => {
return (dispatch: any) => {
dispatch(listEventsRequestedAction());
(API.graphql(graphqlOperation(listEvents)) as Promise<any>).then((results:any) => {
const events = results.data.listEvents.items
dispatch(listEventsReceivedAction(events))
}).catch((err:any) => {
// console.log("ERROR")
dispatch(listEventsErrorAction(err))
})
}
}
P.S. The semicolon is not required in Javascript and would not cause a
js error on its own. It could however cause an error if concatenating
with other scripts.

Property 'findDOMNode' does not exist on type 'typeof React'

I'm trying to study on how to use typescript and react js. I follow this link and I successfully install the files. here's the package.json
{
"name": "proj",
"version": "1.0.0",
"description": "hello world",
"main": "index.js",
"scripts": {
"test": "sample"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/react": "^0.14.55",
"#types/react-dom": "^0.14.19",
"react": "^15.4.1",
"react-dom": "^15.4.1"
},
"devDependencies": {
"awesome-typescript-loader": "^3.0.0-beta.17",
"source-map-loader": "^0.1.5",
"typescript": "^2.1.4",
"webpack": "^1.14.0",
"todomvc-app-css": "^2.0.0",
"todomvc-common": "^1.0.0"
}
}
and here is the code of my tsx.
import * as React from "react";
import * as ReactDOM from "react-dom";
export interface ItemProps { todoItem:string; getIndex:number; onDelete:any; onEdit:any; onChange:number}
interface ItemState {clickEdit:string;text:string}
export class TodoItem extends React.Component<ItemProps, ItemState> {
public state:ItemState;
constructor(props:ItemProps){
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {clickEdit:"",text:this.props.todoItem};
}
public handleChange(e) {
this.setState({text: e.target.value});
}
public handleSubmit(e){
this.setState({clickEdit:""});
}
public delete(){
this.props.onDelete(this.props.getIndex);
}
public edit(){
var node = React.findDOMNode<HTMLInputElement>(this.refs["editField"]);
node.focus();
this.setState({clickEdit:"editing"});
this.props.onEdit(this.props.getIndex);
}
public render() {
return (
<li className={this.state.clickEdit}>
<div className="view">
<label onDoubleClick={e => this.edit()}>{this.props.todoItem}</label>
<button className="destroy" onClick={e => this.delete()}></button>
</div>
<input ref="editField" className="edit" onBlur={e => this.handleSubmit(e)} value={this.state.text} onChange={e => this.handleChange(e)} autoFocus={true} />
</li>
);
}
}
I don't know why I cannot use findDOMNode. I already import the REACT. Do I miss something in my files or there is something that I need to install
try import ReactDOM from 'react-dom'; ReactDOM.findDOMNode().

Categories