Cannot import createSagaMiddleware from 'redux-saga' in my create-react-app - javascript

I have the following import in my create-react-app:
import createSagaMiddleware from 'redux-saga';
Problem is that my system is unable to import createSagaMiddleware.
I am running versions:
node 12.13.0
npm 6.12.1
My package.json looks like this:
{
"name": "foo",
"version": "0.1.0",
"private": true,
"dependencies": {
"firebase": "^7.1.0",
"node-sass": "^4.12.0",
"npm": "^6.12.1",
"react": "^16.10.1",
"react-dom": "^16.10.1",
"react-redux": "^7.1.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.1.2",
"react-stripe-checkout": "^2.6.3",
"redux": "^4.0.4",
"redux-logger": "^3.0.6",
"redux-persist": "^6.0.0",
"redux-saga": "^1.1.1",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"styled-components": "^4.4.0"
},
"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"
]
}
}
My IDE says (Intellij IDEA) says that it 'cannot resolve symbol 'createSagaMiddleware'.
The actual error message that I see is
Error: Actions must be plain objects. Use custom middleware for async actions
which is thrown at
componentDidMount() {
const {fetchCollectionsStart} = this.props;
fetchCollectionsStart();
};
->
const mapDispatchToProps = (dispatch) => ({
fetchCollectionsStart: () => dispatch(fetchCollectionsStart())
});
export default connect(
null,
mapDispatchToProps
)(ShopPage);
The fetchCollectionsStart action looks like this:
import {takeEvery} from 'redux-saga/effects';
import ShopActionTypes from "./shop.types";
export function* fetchCollectionsAsync() {
yield console.log('I am fired');
}
export function* fetchCollectionsStart() {
yield takeEvery(
ShopActionTypes.FETCH_COLLECTIONS_START,
fetchCollectionsAsync
);
}
My redux store looks like this:
import { createStore, applyMiddleware } from 'redux';
import { persistStore } from 'redux-persist';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import {fetchCollectionsStart} from "./shop/shop.sagas";
import rootReducer from './root-reducer';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
if (process.env.NODE_ENV === 'development') {
middlewares.push(logger);
}
export const store = createStore(rootReducer, applyMiddleware(...middlewares));
sagaMiddleware.run(fetchCollectionsStart);
export const persistor = persistStore(store);
export default { store, persistStore };
I have seen a similar question be asked at https://github.com/redux-saga/redux-saga/issues/1967.
However that answer doesn't solve it here.
Any ideas?
Thanks

As the error says, actions have to be plain objects. Apparently you are dispatching a saga instead of an action.
Replace your mapDispatchToProps code block with:
const mapDispatchToProps = (dispatch) => ({
fetchCollectionsStart: () => {
dispatch({ type: ShopActionTypes.FETCH_COLLECTIONS_START });
},
});

Related

Prime React css styles not applying in Reactjs application

I am working on an react js application, I had added reactbootstrap & primereact library for the styling.
the reactbootstrap library is working fine But primereact styling is not getting applied , I have followed all the steps present in getting started section, can anyone suggest me what is missing.
I am adding the Files for the refrence.
I used the below command to add files in node modules
npm install primereact --save
npm install primeicons --save
App.js File
import logo from './logo.svg';
import './App.css';
import Header from './MyComponents/Header'
import 'bootstrap/dist/css/bootstrap.min.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import {Todos} from './MyComponents/Todos'
import {TodoElements} from './MyComponents/TodoElements'
import {Footer} from './MyComponents/Footer'
function App() {
<script src="https://unpkg.com/primereact/primereact.all.min.js"></script>
return (
<><Header title='Code With Shiva' searchBar={true}/>
<Todos/>
<TodoElements/>
<Footer/>
</>
);
}
export default App;
Todos.js where I am adding primereact styled button
import React from 'react';
import { Button } from 'primereact/button';
export const Todos = () => {
return (
<div>
<Button label="Success" className="p-button-success" />
</div>
)
}
Adding package.json for refrence
{
"name": "todos-list",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"bootstrap": "^5.1.3",
"primeicons": "^5.0.0",
"primereact": "^7.1.0",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-bootstrap": "^2.1.1",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"react-transition-group": "^4.4.2",
"style-loader": "^3.3.1",
"web-vitals": "^2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"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"
]
}
}
Adding final result image
All PrimeReact components require a theme so just add...
import "primereact/resources/themes/lara-light-indigo/theme.css";

ReferenceError: expect is not defined in react app

I am developing a react app, suddenly after adding two tests I got an error that is,
ReferenceError: expect is not defined
./node_modules/#testing-library/jest-dom/dist/extend-expect.js
node_modules/#testing-library/jest-dom/dist/extend-expect.js:9
I tried to implement the solutions I found on the internet but nothing is working. Here are my two test files,
1st one,
import React from "react";
import { render, screen, within } from "#testing-library/react";
import Index from "./Index";
describe("<Index/>", () => {
it("checking render", () => {
render(<Index />);
});
});
it("checking text", () => {
const { getByTestId } = render(<Index />);
const { getByText } = within(getByTestId("durbin"));
expect(getByText("DurBinLab-Test")).toBeInTheDocument();
});
And 2nd one is,
import React from "react";
import { render, fireEvent, within, screen } from "#testing-library/react";
import Login from "./Login";
import userEvent from "#testing-library/user-event";
describe("<Login/>", () => {
it("checking render", () => {
render(<Login />);
});
});
it("text check", () => {
const { getByTestId } = render(<Login />);
const { getByText } = within(getByTestId("login"));
expect(getByText("Login")).toBeInTheDocument();
});
describe("Input Field Check", () => {
test("render email input", () => {
render(<Login />);
const inputEl = screen.getByTestId("email-input");
expect(inputEl).toBeInTheDocument();
});
test("pass valid email to test email input field", () => {
render(<Login />);
const inputEl = screen.getByTestId("email-input");
userEvent.type(inputEl, "test#mail.com");
});
Lastly here is my package.json
{
"name": "user-manage",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.4.1",
"#emotion/styled": "^11.3.0",
"#mui/icons-material": "^5.0.0",
"#mui/material": "^5.0.0",
"#testing-library/react": "^12.1.0",
"#testing-library/user-event": "^12.1.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.5",
"react-router-dom": "^5.3.0",
"react-scripts": "4.0.3",
"redux": "^4.1.1",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.3.0",
"uuid": "^3.4.0",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"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": {
"#testing-library/jest-dom": "^5.14.1"
}
}
This is what my JSON file looks like. I tried to edit the setuptest.js file. But the problem is still same.

SyntaxError: Cannot use import statement outside a module when testing using jest and react-testing-library

I am always getting this error whenever trying to test my file using jest and react-testing-library
error --
Details:
/Users/user/dev/system-wheels/src/Constants/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { MAP_API_KEY } from "../config.local";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-cli/node_modules/jest-runtime/build/index.js:1517:14)
at Object.<anonymous> (node_modules/graceful-fs/polyfills.js:1:99)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.777 s
Ran all test suites matching /Loginpage.test.js/i.
error Command failed with exit code 1.
Here is my package.json-
{
"name": "system-wheels",
"version": "0.1.0",
"private": true,
"dependencies": {
"#firebase/app": "^0.6.29",
"#firebase/messaging": "^0.7.15",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^12.0.0",
"#testing-library/user-event": "^13.2.1",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-places-autocomplete": "^7.3.0",
"react-redux": "^7.2.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-window": "^1.8.6",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"storage": "file:./src/Packages/Storage/",
"styled-components": "^5.2.1",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "bash ./scripts/init.sh && react-scripts start",
"build": "bash ./scripts/init.sh && react-scripts build",
"test": "bash ./scripts/init.sh && react-scripts test --transformIgnorePatterns \"node_modules/(?!#toolz/allow-react)/\" --env=jsdom",
"test2": " jest",
"eject": "react-scripts eject"
},
"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"
]
},
"alias": {
"modules": "src/Modules/",
"components": "src/Common/Components/",
"hooks": "src/Hooks/",
"helper": "src/Helper/",
"common": "src/Common/",
"globalStyles": "src/GlobalStyles/",
"constants": "src/Constants/",
"assets": "src/Assets/",
"context": "src/Context/",
"route": "src/Routes/"
},
"devDependencies": {
"#babel/plugin-transform-modules-commonjs": "^7.15.0",
"#babel/plugin-transform-runtime": "^7.15.0",
"#babel/preset-env": "^7.15.0",
"#babel/preset-react": "^7.14.5",
"#babel/runtime": "^7.15.3",
"babel-jest": "^27.1.0",
"jest": "^27.1.0",
"ts-jest": "^27.0.5"
}
}
Here is my - babel.config.js
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-react",
],
};
Here is my - jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "jest-environment-jsdom",
transform: {
"^.+\\.(ts|tsx)?$": "ts-jest",
"^.+\\.(js|jsx)?$": "babel-jest",
},
moduleNameMapper: {
"^constants$": "<rootDir>/src/Constants/",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"^modules(.*)$": "<rootDir>/src/Modules/",
"^helper$": "<rootDir>/src/helper/",
"^context$": "<rootDir>/src/Context/",
"^route(.*)$": "<rootDir>/src/Routes/",
"^assets(.*)$": "<rootDir>/src/Assets/",
"^globalStyles(.*)$": "<rootDir>/src/GlobalStyles/",
"^common(.*)$": "<rootDir>/src/Common/",
"^hooks(.*)$": "<rootDir>/src/Hooks/",
"^components(.*)$": "<rootDir>/src/Common/Components/",
},
};
Here is the unit test
import "#testing-library/jest-dom";
import React from "react";
import { render, fireEvent, waitFor, screen } from "#testing-library/react";
import LoginPage from "../Views/LoginPage";
describe("Login page testing", () => {
let wrapper;
beforeEach(() => {
wrapper = render(<LoginPage />);
});
test("should contain input fields", () => {
screen.getByLabelText("Your Email");
screen.getByLabelText("Password");
});
});
Here is the LoginPage component
import React, { useState, useCallback } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import Form from "./Form";
import { loginUser, updateLoginType } from "../../../Common/ActionCreators";
import useAlert from "../../../Hooks/useAlert";
import Path from "../../../Routes/Path";
import BACK_IMAGE from "../assets/background.png";
import SOFTWARE_IMAGE from "assets/OMS.svg";
import { ViewPortContainer, BackgroundImage, SoftwareLogo } from "../styles";
const { companySelection } = Path.authorized;
const LoginPage = ({ loginUser, history, updateLoginType }) => {
const [inProgress, updateProgress] = useState(false);
const { showAlert } = useAlert();
const navigateToCompanySelectionPage = () => {
history.replace(companySelection.view.path);
};
const onFormSubmit = useCallback(async (values, resetForm) => {
const { login_email, login_password, login_loginAs } = values;
try {
updateProgress(true);
updateLoginType({ isLoggedInAsAdmin: Boolean(login_loginAs) });
await loginUser({
emailOrMobile: login_email.toLowerCase(),
password: login_password,
isAdmin: Boolean(login_loginAs),
});
updateProgress(false);
navigateToCompanySelectionPage();
} catch (err) {
updateProgress(false);
showAlert({ message: err[0], type: "error" });
}
}, []);
return (
<ViewPortContainer>
<SoftwareLogo src={SOFTWARE_IMAGE} />
<BackgroundImage src={BACK_IMAGE} />
<Form onFormSubmit={onFormSubmit} inProgress={inProgress} />
</ViewPortContainer>
);
};
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
loginUser,
updateLoginType,
},
dispatch
);
export default connect(null, mapDispatchToProps)(LoginPage);
I am stuck at this problem for days, please Help

Line 0: Parsing error: Cannot read property 'map' of undefined TypeScript React

I was replacing an app created using React and JS with TypeScript using ts migrate, but the following error occurred in the file App.tsx.
Line 0: Parsing error: Cannot read property 'map' of undefined
The following is App.tsx
import React, { useState, useEffect, useCallback} from 'react';
import './assets/styles/style.css';
import {AnswersList, Chats} from './components/index';
import FormDialog from './components/Forms/FormDialog';
import {db} from './firebase/index';
const App = () => {
const [answers, setAnswers] = useState([]);
const [chats, setChats] = useState([]);
const [currentId, setCurrentId] = useState("init");
const [dataset, setDataset] = useState({});
const [open, setOpen] = useState(false);
interface Dataset {
"answers": Array<Answer>,
"question": string
}
interface Answer {
"answers": [
{"content": string, "nextId": string}
]
}
const displayNextQuestion = (nextQuestionId: string, nextDataset: Dataset) => {
addChats({
text: nextDataset.question,
type: 'question'
})
setAnswers(nextDataset.answers)
setCurrentId(nextQuestionId)
}
const selectAnswer = (selectedAnswer: any, nextQuestionId: any) => {
switch(true) {
case (nextQuestionId === 'contact'):
handleClickOpen()
break;
case (/^https:*/.test(nextQuestionId)):
const a = document.createElement('a');
a.href = nextQuestionId;
a.target = '_blank';
a.click();
break;
default:
addChats({
text: selectedAnswer,
type: 'answer'
})
setTimeout(() => displayNextQuestion(nextQuestionId, dataset[nextQuestionId]), 500)
break;
}
}
const addChats = (chat: any) => {
setChats((prevState) => {
return [...prevChats, chat]
})
}
const handleClickOpen = () => {
setOpen(true)
};
const handleClose = useCallback(() => {
setOpen(false)
}, [setOpen]);
useEffect(() => {
(async() => {
const initDataset = {};
await db.collection('questions').get().then(snapshots => {
snapshots.forEach(doc => {
const id = doc.id
const data = doc.data()
initDataset[id] = data
})
})
setDataset(initDataset)
displayNextQuestion(currentId, initDataset[currentId])
})()
}, [])
useEffect(() => {
const scrollArea = document.getElementById('scroll-area')
if (scrollArea) {
scrollArea.scrollTop = scrollArea.scrollHeight
}
})
return(
<section className="c-section">
<div className="c-box">
<Chats chats={chats} />
<AnswersList answers={answers} select={selectAnswer} />
<FormDialog open={open} handleClose={handleClose} />
</div>
</section>
);
}
export default App;
The following is package.json
{
"name": "chatbot",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^4.11.2",
"#material-ui/icons": "^4.11.2",
"#material-ui/system": "^4.11.2",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-router-dom": "^5.1.6",
"#typescript-eslint/eslint-plugin": "^4.9.0",
"#typescript-eslint/parser": "^4.9.0",
"firebase": "^7.24.0",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-scripts": "3.4.3"
},
"resolutions": {
"#typescript-eslint/eslint-plugin": "^4.1.1",
"#typescript-eslint/parser": "^4.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"ts-loader": "^8.0.11",
"ts-migrate": "^0.1.10",
"typescript": "^4.1.2"
}
}
When I was researching the error, I found this page, so I tried it with reference to it, but it didn't change.
By the way, here's what I tried
Delete the node_modules file and install npm again
Installing #typescript-eslint/eslint-plugin and #typescript-eslint/parser
If you delete the description of the interface Dataset and interface Answer in App.tsx, the relevant error disappears. But another type of error occurs.
I couldn't get a good hint by googling, so I asked this question.
I would appreciate it if you could tell me the cause of this Line 0: Parsing error: Cannot read property 'map' of undefined and more.
You get the error because react-scripts=3.4.3 is not compatible with typescript=^4.1.2. The relevant issue can be found here: https://github.com/facebook/create-react-app/issues/9515
You can solve this by either
Upgrading to react-scripts to >=4.0 (which adds support for TypeScript 4).
Downgrading typescript to <4.

importing any component from react-bootstrap throws error

I have some weird error everytime when I'm trying to use some component from 'react-bootstrap'. Here is some small example where I'm importing "HelpBlock" component.
import PropTypes from 'prop-types';
import React from 'react';
import HelpBlock from 'react-bootstrap';
class RegisterFormDetails extends React.Component {
...
<HelpBlock>{validationErrorMessage}</HelpBlock>
}
</div>
</div>
);
};
export default RegisterFormDetails;
but then I'm getting this error
Attempted import error: 'react-bootstrap' does not contain a default export (imported as 'HelpBlock').
my package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"bootstrap": "^4.3.1",
"lodash": "^4.17.11",
"prop-types": "^15.7.2",
"react": "^16.8.3",
"react-bootstrap": "^0.32.1",
"react-bootstrap-sweetalert": "^4.4.1",
"react-dom": "^16.8.3",
"react-scripts": "^2.1.5",
"react-select": "^2.4.1"
}
}
somebody can help me ? I have rechecked the react-bootstrap folder in node_modules and contains the component which I'm trying to import
You can import individual components like:
import HelpBlock from 'react-bootstrap/HelpBlock ';
The first one is importing component directly, The above is a default import. Default imports are exported with export default .... There can be only a single default export. Since 'react-bootstrap' does not contain a default export , you have to import directly.
or import { HelpBlock } from 'react-bootstrap';
Here, only HelpBlock will be imported. Hope it helps.
This article will help you to understand es6 modules.

Categories

Resources