My ReactJS module page component is not rendering for some reason - reactjs

On my react application, the module page component is not rendering, this is the error is receive when I load the component. In this component, I am trying to read data from the firebase real time database and then display it on the page.
Uncaught ReferenceError: initialize is not defined
I also get this error as well
Uncaught Error: ModulePage(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
The following is my code for the module page component
import Header from './header.js';
import Footer from './footer.js'
import './review_index.css';
import { Card, Button } from "react-bootstrap";
import React, {useEffect, initialize} from 'react';
import { useNavigate} from "react-router-dom";
import {realtimeDB, auth } from '../firebase-config';
import { ref, onValue } from 'firebase/database';
import { useAuthState } from 'react-firebase-hooks/auth';
function ModulePage(){
let navigate = useNavigate();
//if statement that checks if the page is being accessed by the user
const [user] = useAuthState(auth);
if(!user){
navigate("/");
}
//function to get the data
const getData = () => {
const data = ref(realtimeDB, 'Modules')
onValue(data, (snapshot) => {
return(
<>
<Header />
<h1>Welcome to the module page</h1>
<p> on this page, yopu will see the modules that you can currently upload reviews on</p>
<Card className="module_card">
<h2>Module list</h2>
<p>{snapshot.val()}</p>
<Button className="moduleselection" onClick={navigate("/ModuleReviewForm")}> </Button>
</Card>
<div className="moduleselection"></div>
<Footer />
</>
);
})
}
initialize = true
useEffect(() => {
getData();
}, [initialize])
}
export default ModulePage;
I really need help on this, any advice will be much appreciated.

You have this import:
import React, {useEffect, initialize} from 'react';
And initialize does not exist in the React library, remove this one import and declare initialize as a variable on your code.

Related

Not able to Display API Data in react js

Guys I'm attempting to develop a modest film-based project. I have used TMDB Movies to obtain movies. I don't sure where I went wrong because the data in my console is displaying OK, but when I try to map and display that element, I receive an error saying "Movies.map is not a function." Please try to correct my mistake.
Thanks a lot!
enter image description here
`
import "./App.css";
import MemsData from "./Components/MemsData";
import NewMemsData from "./Components/NewMemsData";
import FilterElement from "./Components/FilterElement";
import MovieBox from "./Components/MovieBox";
import { useEffect, useState } from "react";
import Axios from "axios";
function App() {
const API_URL =
"https://api.themoviedb.org/3/movie/popular?api_key=8f11538792fbc26efa63aa919f0844b8";
const [movie, setMovie] = useState([]);
useEffect(() => {
Axios.get(API_URL).then((res) => {
console.log(res);
setMovie(res.data);
});
});
return (
<div className="App">
<h2>Movie Api</h2>
{
movie.map((moviereq, index) => {
return <div key={index}>{moviereq.title}</div>;
})}
</div>
);
}
export default App;
`
You need to go one deeper and access results: setMovie(res.data.results);
Codesandbox link: https://codesandbox.io/s/frosty-voice-hc912d?file=/src/App.js:392-400

why does my react hooks reset to its default values after doing what it's suppose to do?

I rebuild the code taking away the set states from the immediate call. after calling the geographic search function my function does everything it is supposed too. After that though the hooks refresh again to the usestates initial values. I've been on this for 2 days now so i thought it would be okay to ask for help. I don't think its nay external page as everything goes right up until the page refreshes and all the hooks are set to default. its weird because my navbar function works fine. Apologies for those who have already looked at this.
the url to the repository:https://github.com/JonathanDaboush/realtyKingFrontend.git
import React,{useState, useEffect} from "react";
import { flushSync } from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import PropTypes from "prop-types";
import axios from 'axios';
import { default as AreaW} from "../WriteFolder/geographicMainComponents/areaMainComponent.jsx";
import { default as CityW} from "../WriteFolder/geographicMainComponents/cityMainComponent.jsx";
import { default as CountryW} from "../WriteFolder/geographicMainComponents/countryMainComponent.jsx";
import { default as NeighborhoodW} from "../WriteFolder/geographicMainComponents/neighborhoodMainComponent.jsx";
import { default as RegionW} from "../WriteFolder/geographicMainComponents/regionMainComponent.jsx";
import { NavBar } from "../Navbar/navbar.jsx";
import {MenuList} from "./MenuList.jsx";
import GeographicLocationSearch from "./geographicSearchBar.jsx";
import NewObject from "./newObject.jsx";
import { ThemeProvider } from "react-bootstrap";
function Menu(props){
let [supra,setSupra]=useState([]);
let [options,setOptions]=useState([]);
let [searchBar,setSearchBar]=useState([{locations:["country","region","area","city","neighborhood"]}]);
let [category,setCategory]=useState('');
let [value,setValue]=useState('');
let handleSearchBar=(value)=>{
if(value.category==='country'){
setCategory((category)=>{let newValue='region';console.log(newValue);return newValue;});
}
setOptions((options)=>{let newValue=value.kids;console.log(newValue);return newValue;});
setSupra((supra)=>{let newValue=value;console.log(newValue);return newValue;});
getChildren(value.category+"/getById/"+value.id);
}
let handleNavBar=(value)=>{
setCategory((category)=>{let newValue=value;console.log(newValue);return newValue;});
setSupra((supra)=>{let newValue=[];console.log(newValue);return newValue;});
getChildren(category);
}
const getChildren=(value)=>{
let res=axios.get('http://localhost:8080/'+value)
.then
(
function(res){
let list=res.data;
if(list.length===0){
}
else{
if(list[0]!==undefined){
setOptions(options=>{let newValue=list;console.log(newValue);return newValue;});
}
}
})
.catch(function (error) {
console.log(error);
});
}
useEffect(() => {
if(category===''){
category='country';
}
}
, [value]);
return(
<div>
<div>
<NavBar content={searchBar} handleNavBar={handleNavBar} />
</div>
<div>
{ /*this is the call */}
<GeographicLocationSearch handleSearchBar={handleSearchBar}/>
<NewObject {...supra}/>
<MenuList Items={options} kind={category}/>
</div>
</div>
);
}
export default Menu;
The issue here is that useEffect has value in it's dependency array.
This means that if you call setValue, that effect will be rerun. If that's not what you want, you can change the dependency array from [value] to [] and it will only run once when the component mounts.
You're making a call to setValue in the handleSearchBar callback, so when that callback function is called it will fire that effect again.

Uncaught TypeError: Cannot read properties of undefined (reading 'stats')

I'm using an API for fetching data and it works just fine, by the way I'm using redux. when I refresh my project. I get this error. I also Have et loading so when data is not fetched, waits for it. I have no clue what to do.
This is the component which I used data in
import React, { useEffect } from 'react';
import { useSelector, useDispatch} from 'react-redux';
import { Link } from 'react-router-dom';
import millify from 'millify';
//Redux
import { fetchCoins } from "../../redux/coins/coinsAction";
const Homepage = () => {
const dispatch = useDispatch();
const {coins, loading } = useSelector(state => state.coinsState);
useEffect(() => {
dispatch(fetchCoins());
}, [])
console.log(coins);
return (
<>
{
loading ? <h1>Loading...</h1> :
<div>
<h2>Global Crypto Stats</h2>
<div>
<h5>Total Cryptcurrencies</h5>
<span>{millify(coins.data.stats.total)}</span>
<h5>Total Exchanges</h5>
<span>{millify(coins.data.stats.totalExchanges)}</span>
<h5>Total Market cap</h5>
<span>{millify(coins.data.stats.totalMarketCap)}</span>
<h5>Total 24h Volume</h5>
<span>{millify(coins.data.stats.total24hVolume)}</span>
<h5>Total Markets</h5>
<span>{millify(coins.data.stats.totalMarkets)}</span>
</div>
</div>
}
</>
);
};
export default Homepage;
When facing this issue, the main solution is to put "?" before each dots, it should look like this :
coins?.data?.stats?.total
Try this :)

React JS coponent not rendering using map function

I hava a component called videoRow i try to render this component using dummy values now i get data from a useEffect Hook i have to use that data to render my component but when i try to do so it dont show anything. I even try console log to check weather i get my data or not it print my data on console means my useEffect is working But when i try this data on my videoRow component it not show anything
import React, { useState, useEffect } from "react";
import "../css/searchPage.css";
import TuneSharpIcon from "#mui/icons-material/TuneSharp";
import ChannelRow from "./ChannelRow";
import VideoRow from "./VideoRow";
import { selectInput } from "../features/inputSlice";
import { useSelector } from "react-redux";
import Axios from "axios";
function SearchPage() {
const getQuery = useSelector(selectInput);
const API_URL = `https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=4&key=APIKEY&type=video&q=${getQuery.input}`;
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData() {
let request = await Axios.get(API_URL);
setData(request);
}
fetchData();
}, [API_URL]);
console.log(data);
return (
<div className="searchPage">
<div className="filter">
<TuneSharpIcon></TuneSharpIcon>
<h2>FILTERS</h2>
</div>
<hr></hr>
<ChannelRow
image="https://images.indianexpress.com/2022/01/Republic-Day_1200_AP2022.jpg"
channelName="Dummy"
verified
subs="670k"
noOfVideos={567}
desc="You can find awesome programming lessons here! Also, expect programming tips and tricks that will take your coding skills to the ..."
></ChannelRow>
<hr></hr>
{data?.data?.items?.forEach((item) => {
console.log(item.snippet.title);
console.log(item?.snippet.thumbnails.high.url)
console.log(item?.snippet.publishedAt)
console.log(item?.snippet.description)
console.log(item?.snippet.channelTitle)
return(<VideoRow
image={item?.snippet.thumbnails.high.url}
channelName={item?.channelTitle}
timestamp={item?.snippet.publishedAt}
title={item?.snippet.title}
desc={item?.snippet.description}
views="1.4M"
subs="1.4M"
></VideoRow>)
})}
</div>
);
}
export default SearchPage;
Change data?.data?.items?.forEach to data?.data?.items?.map. forEach returns nothing. So, even if you return the component from the callback, forEach will just ignore it. But, map will return all transformed results as an array.
You can read more about lists in react here.

How can I use jest and enzyme to test content generated dynamically?

So, this component "Info" is a container which process some data in order to generate a "Details" children component with some props.
Info.JS
import React from 'react'
import Details from './Details/Details'
import {Card} from 'reactstrap'
import classes from './Info.module.css'
import {connect} from 'react-redux'
const Info = (props)=>{
let itemDetails = 'Item Details'
let items = undefined
if(props.activeTab === '1'){
items = props.shortTerm
} else if (props.activeTab ==='2'){
items = props.mediumTerm
} else if (props.activeTab ==='3'){
items = props.longTerm
}
if(items.length!==0){
itemDetails=(
items.map((i,index)=>{
if(i.id===props.itemIndex){
return <Details
title={i.itemName}
desc={i.itemDesc}
date={"Created at "+i.created}
edited={i.lastEdited}
key={index}/>
}
console.log(itemDetails)
return null
})
)
} else{
return itemDetails = (
<Details
title="Title"
desc="Description"
key={null}
date={null}/>
)
}
return(
<Card className={classes.info}>
{itemDetails}
</Card>
)
}
const mapStateToProps = (state) =>{
return{
shortTerm:state.reducer.items.shortTerm,
mediumTerm:state.reducer.items.mediumTerm,
longTerm:state.reducer.items.longTerm,
activeTab:state.reducer.activeTab,
itemIndex: state.reducer.itemIndex
}
}
export default connect(mapStateToProps)(Info)
Question
How can I make a test in which I can check if any component is being rendered? Or, how can I write a test in which I can check if any "itemDetails" is being rendered?
I tried this, so far, to test if I could find any being rendered but it always return me a error saying "Cannot read property 'find' of undefined".
The test code is this one:
Info.test.js
import React from 'react'
import {Provider} from 'react-redux'
import {configure,shallow,mount,render} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'
import Info from './Info'
import Details from './Details/Details'
configure({adapter:new Adapter()})
describe('<Info />',()=>{
let wrapper
beforeEach(()=>{
wrapper= shallow(<Info/>);
})
it('Should return one Details',()=>{
expect(wrapper.find(Details)).toHaveLength(1)
})
});
So I found an answer,based on this one: Testing React Redux - cannot read properties of undefined, or wrapper undefined
It worked perfectly for me! I happens that, to generate the component, I had to pass some props to the component. This is the setup that I used in order to make the test to work:
import React from 'react'
import {Provider} from 'react-redux'
import {configure,shallow,mount,render} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'
import {Info} from './Info'
import Details from './Details/Details'
configure({adapter:new Adapter()})
const setup=()=>{
let props= {
shortTerm:[],
mediumTerm:[],
longTerm:[],
activeTab:'1',
itemIndex:0
}
let wrapper = shallow(<Info {...props}/>);
return {props, wrapper};
};
describe('<Info />',()=>{
const {wrapper}=setup()
it('Should return one Details Component',()=>{
expect(wrapper.find(Details)).toHaveLength(1)
})
});

Resources