I am writing a test where I need to render a component, but the rendering of my component is not working and I am receiving this error:
Uncaught [TypeError: Cannot read property 'role' of undefined].
This is because in the componentDidMount function in my component I am checking if this.props.authentication.user.role === 'EXPERT'. However, this.props.authentication has user as undefined.
This is the correct initialState for my program, but for the test I want to set my initialState to have a user object. That is why I redefine initialState in my test. However, the component does not render with that new initialState.
Here is the testing file:
import { Component } from '../Component.js';
import React from 'react';
import { MemoryRouter, Router } from 'react-router-dom';
import { render, cleanup, waitFor } from '../../test-utils.js';
import '#testing-library/jest-dom/extend-expect';
afterEach(cleanup)
describe('Component Testing', () => {
test('Loading text appears', async () => {
const { getByTestId } = render(
<MemoryRouter><Component /></MemoryRouter>,
{
initialState: {
authentication: {
user: { role: "MEMBER", memberID:'1234' }
}
}
},
);
let label = getByTestId('loading-text')
expect(label).toBeTruthy()
})
});
Here is the Component file:
class Component extends React.Component {
constructor(props) {
super(props)
this.state = {
tasks: [],
loading: true,
}
this.loadTasks = this.loadTasks.bind(this)
}
componentDidMount() {
if (
this.props.authentication.user.role == 'EXPERT' ||
this.props.authentication.user.role == 'ADMIN'
) {
this.loadTasks(this.props.location.state.member)
} else {
this.loadTasks(this.props.authentication.user.memberID)
}
}
mapState(state) {
const { tasks } = state.tasks
return {
tasks: state.tasks,
authentication: state.authentication
}
}
}
I am also using a custom render function that is below
import React from 'react'
import { render as rtlRender } from '#testing-library/react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { initialState as reducerInitialState, reducer } from './_reducers'
import rootReducer from './_reducers'
import configureStore from './ConfigureStore.js';
import { createMemoryHistory } from 'history'
function render(ui, {
initialState = reducerInitialState,
store = configureStore({}),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}
// re-export everything
export * from '#testing-library/react'
// override render method
export { render }
Perhaps I am coming super late to the party but maybe this can serve to someone. What I have done for a Typescript setup is the following (all this is within test-utils.tsx)
const AllProviders = ({
children,
initialState,
}: {
children: React.ReactNode
initialState?: RootState
}) => {
return (
<ThemeProvider>
<Provider store={generateStoreWithInitialState(initialState || {})}>
<FlagsProvider value={flags}>
<Router>
<Route
render={({ location }) => {
return (
<HeaderContextProvider>
{React.cloneElement(children as React.ReactElement, {
location,
})}
</HeaderContextProvider>
)
}}
/>
</Router>
</FlagsProvider>
</Provider>
</ThemeProvider>
)
}
interface CustomRenderProps extends RenderOptions {
initialState?: RootState
}
const customRender = (
ui: React.ReactElement,
customRenderProps: CustomRenderProps = {}
) => {
const { initialState, ...renderProps } = customRenderProps
return render(ui, {
wrapper: (props) => (
<AllProviders initialState={initialState}>{props.children}</AllProviders>
),
...renderProps,
})
}
export * from '#testing-library/react'
export { customRender as render }
Worth to mention that you can/should remove the providers that doesn't make any sense for your case (like probably the FlagsProvider or the HeaderContextProvider) but I leave to illustrate I decided to keep UI providers within the route and the others outside (but this is me making not much sense anyway)
In terms of the store file I did this:
//...omitting extra stuff
const storeConfig = {
// All your store setup some TS infer types may be a extra challenge to solve
}
export const store = configureStore(storeConfig)
export const generateStoreWithInitialState = (initialState: Partial<RootState>) =>
configureStore({ ...storeConfig, preloadedState: initialState })
//...omitting extra stuff
Cheers! 🍻
I am not sure what you are doing in the configure store, but I suppose the initial state of your component should be passed in the store.
import React from 'react'
import { render as rtlRender } from '#testing-library/react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { initialState as reducerInitialState, reducer } from './_reducers'
import { createMemoryHistory } from 'history'
function render(
ui,
{
initialState = reducerInitialState,
store = createStore(reducer,initialState),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}
// re-export everything
export * from '#testing-library/react'
// override render method
export { render }
I hope it will help you :)
I would like to use some data I received from firestore to build a quiz. Unfortunately I can console.log the array, but if I use .length it is undefined.
Is this problem caused by some lifecycle or asnynchronous issue?
Thanks in advance!
import React, { Component } from 'react';
import { connect } from 'react-redux';
class LernenContainer extends Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
render() {
return (
<div className="lernenContainer">
LernenContainer
{
console.log(this.props.firestoreData),
// prints array correctly
console.log(this.props.firestoreData.length)
// is undefined
}
</div>
);
}
}
const mapStateToProps = state => {
return {
firestoreData: state.firestoreData
};
};
const mapDispatchToProps = dispatch => {
return {
// todo Achievements
};
};
export default connect(mapStateToProps, mapDispatchToProps) (LernenContainer);
console.log(this.props.firestoreData):
Try below code
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types'
class LernenContainer extends Component {
constructor(props) {
super(props);
}
static propTypes = {
firestoreData: PropTypes.object.isRequired
}
render() {
const { firestoreData } = this.props
console.log(firestoreData);
console.log(firestoreData.length);
return (
<div className="lernenContainer">
</div>
);
}
}
const mapStateToProps = (state) => ({
firestoreData: state.firestoreData
})
const mapDispatchToProps = (dispatch) => ({
})
export default connect(mapStateToProps,mapDispatchToProps)(LernenContainer);
I have this main component which is connected to the redux store via connect method.
I am also using logger middleware in order to check the store state as it progressively changes and from there i can see the store is updating successfully but the component it is connected is not re rendering.
Please help....
I have tried almost everything including using Object.assign({}), spread operation and also tried using the componentWillReceiveProps(nextProps) but still the ui is not updating.
Here is the Main app.js file:
import React from 'react'
import { render } from 'react-dom'
import App from './MainComponent'
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import { reactReduxFirebase, getFirebase, firebaseReducer } from 'react-redux-firebase';
import firebase from './fbConfig'
import usersReducer from './reducers/usersReducer'
import logger from 'redux-logger'
// const rootReducer = combineReducers({
// firebase: firebaseReducer,
// });
const data = window.data;
delete window.data;
const store = createStore(usersReducer, data, applyMiddleware(logger(), thunk));
store.subscribe(() => {
// console.log("Store State : " + JSON.stringify(store.getState()));
});
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
)
where data is
{"users":[{"key":1,"value":{"employeeID":1,"firstName":"Siddharth Kilam","mobileNumber":"+919987792049","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-09 09:15:05","lat":28.4453983,"lon":77.1012133,"eventTypeID":9,"employeeID":1},"attendanceRow":{"timestamp":"2019-04-09 09:05:39","lat":28.4453983,"lon":77.1012133,"eventTypeID":8,"employeeID":1},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"2019-04-11T04:34:00.000Z","endTime":"2019-04-11T12:34:00.000Z"}]},"offlinePeriod":3600000,"status":"Inactive"}},{"key":145,"value":{"employeeID":145,"firstName":"SidKilam2 Motorola","mobileNumber":"9599936991","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-03 12:20:16","lat":28.4455203,"lon":77.101336,"eventTypeID":9,"employeeID":145},"attendanceRow":{"timestamp":"2019-04-02 23:01:27","lat":28.4747009,"lon":77.0989274,"eventTypeID":9,"employeeID":145},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"1999-12-31T18:30:00.000Z","endTime":"2000-01-01T18:29:59.000Z"}]},"offlinePeriod":3600000,"status":"Offline"}}]};
Reducer file is
const GET_TASKS = 'get tasks'
export default (state = {}, action) => {
switch (action.type) {
case GET_TASKS:
// return state.usersList.map(emp => {
// return Object.assign({}, emp.value, {
// firstName : "Neeraj Kumar Bansal"
// })
// });
return { ...state, tasks : action.tasks }
default:
return state;
}
}
Action File Is
import database from '../fbConfig'
/**
* ACTION TYPES
*/
const GET_TASKS = 'get tasks'
/**
* ACTION CREATORS
*/
export const getTasks = (tasks) => ({type: GET_TASKS, tasks})
/**
* THUNKS
*/
export function getTasksThunk() {
return dispatch => {
const tasks = [];
database.ref(`/tasks/145/2019-01-14`).once('value', snap => {
// console.log("Called ......................");
snap.forEach(data => {
let task = data.val();
tasks.push(task)
})
// console.log("Tasks Fetched" + tasks);
})
.then(() => dispatch(getTasks(tasks)))
}
}
UI Component IS :
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { firebaseConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import MapView from './components/map/MapView'
import MapComponents from './components/map/MapComponents';
import TasksSidebar from './components/map/TasksSidebar';
import { getTasksThunk } from './thunks/getTasksThunk'
class App extends Component {
render() {
// console.log("Props From Main Component : " + JSON.stringify(this.props.users));
const { users } = this.props;
// const { tasks } = this.state;
console.log("Users From Main Component : " + users);
// console.log("Tasks From Main Component : " + tasks);
return (
<div>
<MapComponents users={users} />
<TasksSidebar />
<MapView users={users}/>
</div>
);
}
}
// export default compose(
// firebaseConnect((props) => {
// return [
// 'Tasks'
// ]
// }),
// connect(
// (state) => ({
// tasks: state.firebase.data.Tasks,
// // profile: state.firebase.profile // load profile
// })
// )
// )(App)
const mapStateToProps = function(state) {
console.log("Map State to props : " + state);
return {
users : state.users,
tasks : state.tasks
}
}
const mapDispatch = dispatch => {
dispatch(getTasksThunk())
return {
}
}
export default connect(mapStateToProps, mapDispatch)(App);
The UI should re render as the store state changes....
Use static getDerivedStateFromProps lifecycle component. As it executes for each re-rendering.
You may check the condition there, if there are no changes just return null otherwise update the state there. In getDerived state from props, you may set the state by returning an object. the setState function won't work here, since it is a static method. kindly refer this link https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
// alter your store and reducer file
const store = createStore(usersReducer, applyMiddleware(logger(), thunk));
const GET_TASKS = 'get tasks';
const initialState = {
users: [{"key":1,"value":{"employeeID":1,"firstName":"Siddharth Kilam","mobileNumber":"+919987792049","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-09 09:15:05","lat":28.4453983,"lon":77.1012133,"eventTypeID":9,"employeeID":1},"attendanceRow":{"timestamp":"2019-04-09 09:05:39","lat":28.4453983,"lon":77.1012133,"eventTypeID":8,"employeeID":1},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"2019-04-11T04:34:00.000Z","endTime":"2019-04-11T12:34:00.000Z"}]},"offlinePeriod":3600000,"status":"Inactive"}},{"key":145,"value":{"employeeID":145,"firstName":"SidKilam2 Motorola","mobileNumber":"9599936991","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-03 12:20:16","lat":28.4455203,"lon":77.101336,"eventTypeID":9,"employeeID":145},"attendanceRow":{"timestamp":"2019-04-02 23:01:27","lat":28.4747009,"lon":77.0989274,"eventTypeID":9,"employeeID":145},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"1999-12-31T18:30:00.000Z","endTime":"2000-01-01T18:29:59.000Z"}]},"offlinePeriod":3600000,"status":"Offline"}}],
tasks: []
}
export default (state = initialState, action) => {
switch (action.type) {
case GET_TASKS:
return { ...state, tasks : action.tasks }
default:
return state;
}
}
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { firebaseConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import MapView from './components/map/MapView'
import MapComponents from './components/map/MapComponents';
import TasksSidebar from './components/map/TasksSidebar';
import { getTasksThunk } from './thunks/getTasksThunk'
class App extends Component {
constructor(){
super();
this.state = {
users: []
}
}
static getDerivedStateFromProps(props, state){
if(props.users !== state.users){
return {
users: props.users // This will update the props value for users in state
}
}
return null;
}
render() {
// console.log("Props From Main Component : " + JSON.stringify(this.props.users));
const { users } = this.state;
// const { tasks } = this.state;
console.log("Users From Main Component : " + users);
// console.log("Tasks From Main Component : " + tasks);
return (
<div>
<MapComponents users={users} />
<TasksSidebar />
<MapView users={users}/>
</div>
);
}
}
const mapStateToProps = function(state) {
//console.log("Map State to props : " + state);
return {
users : state.users,
tasks : state.tasks
}
}
const mapDispatch = dispatch => {
dispatch(getTasksThunk())
return {
}
}
export default connect(mapStateToProps, mapDispatch)(App);
From Party.Container where is connected Party with mapStateToProps and mapDispatchToProps, are sent two functions to Party (fetchData and fetchFooter)
They worked until I implemented in project eslint:"airbnb", and now it's constantly getting this error "Must use destructuring props assignment react/destructuring-assignment".
const mapActionsToProps = {
fetchData,
fetchDataFooter,};
--- these are functions
componentDidMount() {
this.props.fetchData();
this.props.fetchDataFooter(); }
This is the component
import { connect } from 'react-redux';
import { fetchData, fetchDataFooter } from './actions';
import Party from './Party';
const mapStateToProps = state => ({
wishlist: state.wishlist,
cart: state.cart,
});
const mapActionsToProps = {
fetchData,
fetchDataFooter,
};
export default connect(mapStateToProps, mapActionsToProps)(Party);
This is COntainer
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from '../../components/Header/Header';
import Content from './Content/Content.Container';
import styles from './Party.module.scss';
import Footer from '../../components/Footer/Footer';
const propTypes = {
wishlist: PropTypes.shape.isRequired,
cart: PropTypes.shape.isRequired,
// fetchData: PropTypes.func.isRequired,
// fetchDataFooter: PropTypes.func.isRequired,
};
class Party extends Component {
componentDidMount() {
// this.props.fetchData();
// this.props.fetchDataFooter();
}
render() {
const { wishlist, cart } = this.props;
let name;
let profilePicture;
let personWishlist;
let purchases;
let id;
if (wishlist.isFulfilled === true) {
const listId = wishlist.payloadData.data.filter(x => x.id === 1);
({ name } = listId[0].name);
({ profilePicture } = listId[0].picture);
({ personWishlist } = listId[0].wishList);
({ purchases } = listId[0].purchases);
({ id } = listId[0].id);
}
console.log(wishlist, cart);
return (
<div className={styles.Party}>
<Header />
<Content
name={name}
id={id}
profilePicture={profilePicture}
personWishlist={personWishlist}
purchases={purchases}
/>
<Footer
cart={cart}
/>
</div>
);
}
}
Party.propTypes = propTypes;
export default Party;
Can you try the one in below in your componentDidMount method as the error suggests:
componentDidMount() {
const { fetchData, fetchDataFooter } = this.props;
fetchData();
fetchDataFooter();
}
Actually, it means that your expressions should be destructured before usage.
E.g.: you're using:
...
this.props.fetchData();
this.props.fetchDataFooter();
...
You have to change it to:
const { fetchData, fetchDataFooter } = this.props;
fetchData();
fetchDataFooter();
Another solution is to disable this if you want to in your rules file.
"react/destructuring-assignment": [<enabled>, 'always'] - can be always or never.
See here for more information.
I'm using react-lifecycle-component in my react app, and incurred in this situation where I need the componentDidMount callback to load some data from the backend. To know what to load I need the props, and I can't find a way to retrieve them.
here's my container component:
import { connectWithLifecycle } from "react-lifecycle-component";
import inspect from "../../../libs/inspect";
import fetchItem from "../actions/itemActions";
import ItemDetails from "../components/ItemDetails";
const componentDidMount = () => {
return fetchItem(props.match.params.number);
};
// Which part of the Redux global state does our component want to receive as props?
const mapStateToProps = (state, props) => {
return {
item: state.item,
user_location: state.user_location
};
};
// const actions = Object.assign(locationActions, lifecycleMethods);
export default connectWithLifecycle(mapStateToProps, { componentDidMount })(
ItemDetails
);
Any clues?
thanks.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import fetchItem from '../actions/itemActions'
class Container extends Component {
state = {
items: []
}
componentDidMount() {
const { match } = this.props
fetchItem(match.params.number)
// if your fetchItem returns a promise
.then(response => this.setState({items: response.items}))
}
render() {
const { items } = this.state
return (
<div>
{ items.length === 0 ? <h2>Loading Items</h2> :
items.map((item, i) => (
<ul key={i}>item</ul>
))
}
</div>
)
}
const mapStateToProps = (state, props) => {
return {
item: state.item,
user_location: state.user_location
}
}
export default connect(mapStateToProps)(Container)
Though I don't see where you are using the props you take from your Redux store...