I am trying to render data from mongodb server to react app. And it's not working - javascript

This is the console log error
Uncaught Error: Objects are not valid as a React child (found: object with keys {_id, inputText, __v}). If you meant to render a collection of children, use an array instead.
at throwOnInvalidObjectType (react-dom.development.js:14887:1)
at reconcileChildFibers (react-dom.development.js:15828:1)
at reconcileChildren (react-dom.development.js:19167:1)
at updateHostComponent (react-dom.development.js:19924:1)
at beginWork (react-dom.development.js:21618:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
I am being able to save my input to the server but am getting error while trying to fetch it.
Here's the component which is supposed to return the list.
import React, { useState, useEffect } from "react";
import ToDoItem from "./ToDoItem";
import InputArea from "./InputArea";
import "bootstrap/dist/css/bootstrap.min.css";
import axios from "axios";
const ToDoList = () => {
const [x, setX] = useState([]);
const xList = () => {
return x.map((y,index) => {
return <ToDoItem key={index} text={y} />;
});
};
useEffect(() => {
axios
.get("http://localhost:5000/")
.then((res) => {
setX(res.data);
})
.catch((err) => console.log(err));
}, []);
return (
<div className="container">
<div className="heading">
<h1>To-Do List</h1>
</div>
<InputArea />
<div>{xList()}</div>
</div>
);
};
export default ToDoList;

That specific error usually occurs when you are trying to print out an entire object instead of lets say the properties from each object.
Can you console.log the list and let us know what properties you have for each object?

Related

My react project does not render properly when I change a category

ok so I have this code (I'm using firebase) and this is my component Cards, I have another Component which has a link button that leads to another cathegory of my store, but in this code when I try to render the cathegory which is supposed to lead to, it doesnt render anything
import Card from "react-bootstrap/Card";
import { collection, getDocs} from "firebase/firestore";
import { db } from "../firebaseConfig/firebase.js";
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "./Cards.css"
import { useParams } from "react-router-dom";
const Cards = () => {
const [products, setProducts] = useState([]);
const productsCollection = collection(db, "zproducts");
const categoria = useParams()
const getProducts = async () => {
const data = await getDocs(productsCollection);
if(categoria.category){
const dataCategory = data.docs.map((doc) => ({ ...doc.data(), id: doc.id }))
setProducts(dataCategory.filter(i=> i.category == categoria.category))
console.log(products)
}else {
setProducts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
}
}
useEffect(()=>{
getProducts()
},[categoria.category])
return (
<>
<div className="d-flex flex-wrap justify-content-center">
{products.map((product) => (
<Card className="card" key={product.id} style={{ width: "18rem" }}>
<Card.Img variant="top" className="cardImg" src={product.imgProduct} />
<Card.Body>
<Card.Title>{product.name}</Card.Title>
<div className="d-flex justify-content-around">
<Link variant="primary" className="btn btn-dark boton btnDetalles" to={`/Item/${product.id}`}>Ver Detalles</Link>
</div>
</Card.Body>
</Card>
))}
</div>
</>
);
}
export default Cards;
also when I open the console, I have a bunch of errors for some reasons
Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf')
at rt.fromString (bundle.js:2286:13)
at Aa (bundle.js:18047:18)
at ItemDetailContainer (bundle.js:168:73)
at renderWithHooks (bundle.js:53227:22)
at mountIndeterminateComponent (bundle.js:56513:17)
at beginWork (bundle.js:57809:20)
at HTMLUnknownElement.callCallback (bundle.js:42819:18)
at Object.invokeGuardedCallbackDev (bundle.js:42863:20)
at invokeGuardedCallback (bundle.js:42920:35)
at beginWork$1 (bundle.js:62794:11)
bundle.js:55331 The above error occurred in the <ItemDetailContainer> component:
at ItemDetailContainer (http://localhost:3000/static/js/bundle.js:166:80)
at RenderedRoute (http://localhost:3000/static/js/bundle.js:67267:5)
at Routes (http://localhost:3000/static/js/bundle.js:67732:5)
at Router (http://localhost:3000/static/js/bundle.js:67670:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:65875:5)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError # bundle.js:55331
bundle.js:49671 Uncaught TypeError: Cannot read properties of undefined (reading 'indexOf')
at rt.fromString (bundle.js:2286:13)
at Aa (bundle.js:18047:18)
at ItemDetailContainer (bundle.js:168:73)
at renderWithHooks (bundle.js:53227:22)
at mountIndeterminateComponent (bundle.js:56513:17)
at beginWork (bundle.js:57809:20)
at beginWork$1 (bundle.js:62772:18)
at performUnitOfWork (bundle.js:62041:16)
at workLoopSync (bundle.js:61964:9)
at renderRootSync (bundle.js:61937:11)
my github link to the proyect: https://github.com/LeandroMore1/PreEntrega2-More

map not defined in my react after bring data from database

i have a website with api to get movies,i have a user in my web and this user can like a movie and get him into his favorite. then he have a commponent that call favorite and i want to do there a get request from my data base and bring him the title of my movie.after he get the title i do in my useeffect an api request to get the poster and all the details of the movie and then i wanna to show it in my favorite useing map function.
but i have a problem
my map dosent work or if it work he dosent bring the data from the api
this is the favorite componnent
import { getAllFavorite } from "../../service/favServics";
import { useState, useEffect } from "react";
import PageHeader from "../common/pageHeader";
import FavoriteChiled from "./favoritechild";
function Favorite() {
const [favorite, setFavorite] = useState([]);
const [movies, setMovies] = useState([]);
const [data, setData] = useState([]);
async function getAll() {
const { data } = await getAllFavorite();
setFavorite(data);
for (let i = 0; i < data.length; i++) {
const url = `http://www.omdbapi.com/?s=${data[i]}&apikey=aea06659`;
const response = await fetch(url);
const responseJson = await response.json();
const obj = responseJson.Search[0];
if (responseJson.Search) {
setMovies(obj.Title);
}
}
}
useEffect(() => {
getAll(favorite);
}, []);
This is the return of favorite component
<div className="row">
{movies.map((movie) => (
<FavoriteChiled movie={movie} />
))}
</div>
this is the child componnent
function FavoriteChiled(props) {
let { movies } = props;
return (
<>
<div key={movies.imdbID} className="image-container d-flex justify-content-start m-3">
<img src={movies.Poster} alt="movie"></img>
</div>
</>
);
}
the console error
favorite.jsx:32 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at Favorite (favorite.jsx:32:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)`
or this error
favorite.jsx:32 Uncaught TypeError: movies.map is not a function
at Favorite (favorite.jsx:32:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)`

though setting keyExtractor, I'm getting VirtualizedList: missing keys for items, make sure to specify a key or provide a custom keyExtractor

I've set a custom Key extractor for the orders items in the cart, also getting VirtualizedList: missing keys for items, make sure to specify a key or id property on each item or provide a custom key extractor.
Here is code for the orders page.
import React, { useState, useCallback} from "react"
import { View, FlatList, Text} from "react-native"
import axios from "axios"
import baseURL from "../../assets/common/baseUrl"
import { useFocusEffect } from "#react-navigation/native"
import OrderCard from "../../Shared/OrderCard"
const Orders = (props) => {
const [orderList, setOrderList] = useState();
useFocusEffect(
useCallback(
() => {
getOrders();
return () => {
setOrderList();
}
},
[],
)
)
const getOrders = () => {
axios
.get(`${baseURL}orders`)
.then((x) => {
setOrderList(x.data);
})
.catch((error) => console.log(error))
}
return (
<View>
<FlatList
data={orderList}
renderItem={({ item }) => (
<OrderCard navigation={props.navigation} {...item} editMode={true}/>
)}
keyExtractor={(item) => item.id}
/>
</View>
)
}
export default Orders;
After placing the orders by adding item to the cart,
There is no error shown or pop up in the mobile app,
The error is shown in the console where the react-native app is run
VirtualizedList: missing keys for items, make sure to specify a key or id property on each item or provide a custom keyExtractor.,
at node_modules\react-native\Libraries\LogBox\LogBox.js:117:10 in registerWarning
at node_modules\react-native\Libraries\LogBox\LogBox.js:63:8 in warnImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:36:4 in console.warn
at node_modules\expo\build\environment\react-native-logs.fx.js:18:4 in warn
at node_modules\react-native\Libraries\Lists\VirtualizedList.js:1075:8 in render
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:12479:21 in finishClassComponent
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:12404:43 in updateClassComponent
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:19182:22 in beginWork$1
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18086:22 in performUnitOfWork
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18014:38 in workLoopSync
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17978:18 in renderRootSync
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17675:33 in performSyncWorkOnRoot
at [native code]:null in performSyncWorkOnRoot
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5322:31 in runWithPriority$argument_1at node_modules\scheduler\cjs\scheduler.development.js:653:23 in unstable_runWithPriority
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5317:21 in flushSyncCallbackQueueImplat node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5305:28 in flushSyncCallbackQueue
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17719:28 in batchedUpdates$1
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:2492:29 in batchedUpdates
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:2638:16 in _receiveRootNodeIDEvent
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:2767:27 in receiveTouches
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
at [native code]:null in callFunctionReturnFlushedQueue
Here is the picture for it

Invalid Hook call in a functional element

I'm getting this annoying error, but don't know why.
I have 2 functional elements, just starting for test purposes.
Main:
import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom';
import MapaLogisplan from './Layout/MapaLogisplan'
//import DlgInfo from './Layout/DlgInfo'
//import MenuGeneral from './layout/MenuGeneral'
import ReadDlgInfoData from './data/DlgInfoData.js'
const LogisplanMain = () => {
const [TrucksData, setTrucksData] = useState([]);
const [TrucksColumnas, setTrucksColumnas] = useState([]);
//se llama cuando se renderiza. (el return la llama).
useEffect(() => {
const [ datos, columnas ] = ReadDlgInfoData({ Nombredatos: 'Trucks', Matricula: '' });
setTrucksData(datos);
setTrucksColumnas(columnas);
}, []);
return (
<div>
<MapaLogisplan />
</div>
);
}
ReactDOM.render(<LogisplanMain />, document.getElementById('root'));
And
import React, { useState } from 'react';
import soapRequest from 'easy-soap-request';
import XMLParser from 'react-xml-parser';
//PROPS:{Nombredatos(WS),TruckPlate===""->Todos.}
const ReadDlgInfoData = (props) => {
const [datos, setDatos] = useState([]);
const [columnas, setColumnas] = useState([]);
const url = `http://DAVID-PC:800`;
const sampleHeaders = {
'user-agent': 'sampleTest',
'Content-Type': 'text/xml',
'soapAction': 'Da igual',
'Access-Control-Request-Headers': 'Origin, X-Requested-With, Content-Type, Accept, *'
};
.....
I can't find why it complains about:
**Uncaught 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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at Object.throwInvalidHookError (react-dom.development.js:14906)
at useState (react.development.js:1508)
at ReadDlgInfoData (DlgInfoData.js:23)
at app.tsx:15
at invokePassiveEffectCreate (react-dom.development.js:23487)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
at invokeGuardedCallback (react-dom.development.js:4056)
at flushPassiveEffectsImpl (react-dom.development.js:23574)
at unstable_runWithPriority (scheduler.development.js:646)
throwInvalidHookError # react-dom.development.js:14906
useState # react.development.js:1508
ReadDlgInfoData # DlgInfoData.js:23
(anónimo) # app.tsx:15
Any tip of light on how to get it corrected would be appreciated, as I'm starting to work with React I'm lost.
I've checked the 3 possible causes but didn't find anything.
React and React-Dom are 17.0 versions.
I call useState and useEffect at the top of their respective functional elements.
I think I'm not using React in more than one place. If I delete the second import in the
ReadDlgInfoData functional component nothing changes.
So I'm stuck at this point and I have tried all the things I know I can try.
Invalid Hook:
useEffect(() => {
const [ datos, columnas ] = ReadDlgInfoData({ Nombredatos: 'Trucks', Matricula: '' });
setTrucksData(datos);
setTrucksColumnas(columnas);
}, []);
Here is the problem, you destructure your values inside of useEffect, which is against hook rules.
const [ datos, columnas ] = ReadDlgInfoData({ Nombredatos: 'Trucks', Matricula: '' });
useEffect(() => {
setTrucksData(datos);
setTrucksColumnas(columnas);
}, []);
This should solve your problem.

How to test nested connected components using Enzyme?

I am trying to test nested connected components (Redux connected):
The Main component has Container component and are provided by store wrapper in App.
import React, { Component } from 'react';
import Main from './components/Main';
import './App.css';
import { Provider } from 'react-redux'
import createStore from './redux'
import applyConfigSettings from './config'
// Apply config overrides
applyConfigSettings()
const store = createStore()
class App extends Component {
render() {
return (
<Provider store={store}>
<Main/>
</Provider>
);
}
}
export default App;
Main.js
import React, { Component } from 'react';
import logo from '../logo.svg';
import { connect } from 'react-redux'
import Container from './Container'
export class Main extends Component {
render(){
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Pomodoro App</h1>
</header>
<Container/>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
fetching: state.user.fetching,
}
}
const mapDispatchToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Main)
Container.js
import React, { Component } from 'react';
import Grid from 'material-ui/Grid';
import { connect } from 'react-redux'
export class Container extends Component{
render(){
return (
<div className="grid-root">
</div>
)
}
}
const mapStateToProps = (state) => {
return {
fetching: state.user.fetching,
}
}
const mapDispatchToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Container)
All this is created using Create-react-app library. I have installed Enzyme too for testing. Here is my test file for Main.test.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import {Main} from '../../components/Main'
import ContainerConnect, {Container} from '../../components/Container';
import configureStore from 'redux-mock-store';
import { Provider, connect} from 'react-redux';
describe('Main', () => {
let wrapper;
let mountWrapper;
it('wraps all the contents in a div with .App class', () => {
wrapper = shallow(<Main />);
expect(wrapper.find('.App').length).toEqual(1);
});
it('wraps content of header in a div with .App-header class', () => {
wrapper = shallow(<Main />);
expect(wrapper.find('.App-header').length).toEqual(1);
});
it('mount', () => {
const middlewares = [];
const mockStore = configureStore(middlewares);
const initialState = {}
const store = mockStore(initialState)
mountWrapper = mount(
<Provider store={store}>
<Main />
</Provider>
);
});
})
I get following error for the last test:
FAIL src/tests/components/Main.test.js
● Console
console.error node_modules/react-dom/cjs/react-dom.development.js:9643
The above error occurred in the <Connect(Container)> component:
in Connect(Container) (at Main.js:16)
in div (at Main.js:11)
in Main (at Main.test.js:31)
in Provider (created by WrapperComponent)
in WrapperComponent
Consider adding an error boundary to your tree to customize error handling behavior.
Visit some link to fb to learn more about error boundaries.
● Main › mount
TypeError: Cannot read property 'fetching' of undefined
at Function.mapStateToProps [as mapToProps] (src/components/Container.js:18:30)
at mapToPropsProxy (node_modules/react-redux/lib/connect/wrapMapToProps.js:54:92)
at Function.detectFactoryAndVerify (node_modules/react-redux/lib/connect/wrapMapToProps.js:63:19)
at mapToPropsProxy (node_modules/react-redux/lib/connect/wrapMapToProps.js:54:46)
at handleFirstCall (node_modules/react-redux/lib/connect/selectorFactory.js:37:18)
at pureFinalPropsSelector (node_modules/react-redux/lib/connect/selectorFactory.js:85:81)
at Object.runComponentSelector [as run] (node_modules/react-redux/lib/components/connectAdvanced.js:43:25)
at Connect.initSelector (node_modules/react-redux/lib/components/connectAdvanced.js:195:23)
at new Connect (node_modules/react-redux/lib/components/connectAdvanced.js:136:15)
at constructClassInstance (node_modules/react-dom/cjs/react-dom.development.js:6801:20)
at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:8336:9)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:8982:16)
at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:11814:16)
at workLoop (node_modules/react-dom/cjs/react-dom.development.js:11843:26)
at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:11874:9)
at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:12449:24)
at performWork (node_modules/react-dom/cjs/react-dom.development.js:12370:9)
at performSyncWork (node_modules/react-dom/cjs/react-dom.development.js:12347:5)
at requestWork (node_modules/react-dom/cjs/react-dom.development.js:12247:7)
at scheduleWorkImpl (node_modules/react-dom/cjs/react-dom.development.js:12122:13)
at scheduleWork (node_modules/react-dom/cjs/react-dom.development.js:12082:12)
at scheduleRootUpdate (node_modules/react-dom/cjs/react-dom.development.js:12710:5)
at updateContainerAtExpirationTime (node_modules/react-dom/cjs/react-dom.development.js:12738:12)
at Object.updateContainer (node_modules/react-dom/cjs/react-dom.development.js:12765:14)
at ReactRoot.Object.<anonymous>.ReactRoot.render (node_modules/react-dom/cjs/react-dom.development.js:16069:15)
at node_modules/react-dom/cjs/react-dom.development.js:16488:14
at Object.unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:12557:12)
at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:16484:17)
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:16543:12)
at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:218:50)
at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:98:16)
at mount (node_modules/enzyme/build/mount.js:19:10)
at Object.it (src/tests/components/Main.test.js:29:42)
at new Promise (<anonymous>)
at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
Is it so hard to test nested connected components? I have to go and use more of it going forward in the application as well. And also does this mean that testing button clicks and all is harder to test as well?
Based on what you are trying to test, you should not have to deal with redux at all.
Since you are testing your <Main /> component and whether it renders the header properly, just mock your <Container /> completely:
jest.mock('../../components/Container', () => ()=> <div id="mockContainer">
mockContainer
</div>);
Then you can shallow mount your <Main /> without worrying about redux.
After that, when you start unit testing your <Container />, just unit test the React.Component class and do not bother with the connected Component, testing it is redundant.
In other words, you should be able to test any React app without ever having to mock the redux store. Just mock connected components entirely.
More info here

Categories

Resources