Not able to Display API Data in react js - reactjs

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

Related

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 :)

My ReactJS module page component is not rendering for some reason

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.

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.

React Typescript - Error Objects are not valid as a React child

I trying to Fetch data from Random user API, but I get the following error:
"Objects are not valid as a React child (found: object with keys {title, first, last}). If you meant to render a collection of children, use an array instead."
Here my code so far:
import "./styles.css";
import React, { useState, useEffect } from "react";
import { User } from "../interfaces/users";
import axios, { AxiosResponse } from "axios";
export default function App() {
const [randomUsers, setRandomUsers] = useState<User[]>([]);
useEffect(() => {
axios
.get<User[]>("https://randomuser.me/api/?results=20")
.then((response: AxiosResponse) => {
setRandomUsers(response.data.results);
});
}, []);
return (
<div className="App">
<h1>Names from random user API</h1>
<ul>
{randomUsers.map((user, key) => (
<li key={key}>{user.name}</li>
))}
</ul>
</div>
);
}
I don't understand why I can't map randomUsers
Here the code sandbox:
Any help will be appreciated
you are facing this error because names is an object so try this
<li key={key}>{user.name.first}</li>

How to render an object of arrays with useEffect

I can't seem to get my object of arrays working. I want to pass an array from an api into a setstate function to turn that state into an array. Then iterate over that array. iterating should give me access to the object's properties. I want to access unique object properties to return and render them into my component. However, I get an error "Object Expected".
import React,{useState,useEffect} from 'react';
import './App.css';
import { CharacterComponent } from "../src/CharacterComponent"
import axios from "axios"
import ReactDOM from "react-dom";
export const Characters = () => {
// Try to think through what state you'll need for this app before starting. Then build out
// the state properties here.
// Fetch characters from the star wars api in an effect hook. Remember, anytime you have a
// side effect in a component, you want to think about which state and/or props it should
// sync up with, if any.
const [character,setCharacter] = useState({})
useEffect( () => {
axios.get("https://swapi.co/api/people")
.then(res => setCharacter(res.data.results) )
},[])
(console.log(character))
return (
<>
<div>
{character.map((element,index) => <CharacterComponent id={element} key={index} />)}
</div>
</>
)
}
That's weird, seems to be working fine in this sandbox: https://codesandbox.io/s/lingering-brook-veo3f
I initialized the state as an empty array as well:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import CharacterComponent from "./CharacterComponent";
import "./styles.css";
function App() {
const [character, setCharacter] = useState([]);
useEffect(() => {
axios
.get("https://swapi.co/api/people")
.then(res => setCharacter(res.data.results));
}, []);
return (
<div className="App">
{character.map(item => (
<CharacterComponent id={item} />
))}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Maybe take a look to see if there's something wrong with your child component:
import React from "react";
const CharacterComponent = ({ id }) => {
return <div>{id.name}</div>;
};
export default CharacterComponent;

Resources