Why can't I render multiple cards using map? - javascript

I'm trying to render multiple cards by pulling data from the API. But the return is an array, I don't understand why the map is not working.
const CharacterCard = () => {
const [showModal, setShowModal] = useState(false)
const openModal = () => {
setShowModal(prev => !prev)
}
const characters = useRequestData([], `${BASE_URL}/characters`)
const renderCard = characters.map((character) => {
return (
<CardContainer key={character._id} imageUrl={character.imageUrl}/>
)
})
return (
<Container>
{renderCard}
<ModalScreen showModal={showModal} setShowModal={setShowModal} />
</Container>
)
}
export default CharacterCard
The hook is this
import { useEffect, useState } from "react"
import axios from "axios"
const useRequestData = (initialState, url) => {
const [data, setData] = useState(initialState)
useEffect(() => {
axios.get(url)
.then((res) => {
setData(res.data)
})
.catch((err) => {
console.log(err.data)
})
}, [url])
return (data)
}
export default useRequestData
console error image
requisition return image
API: https://disneyapi.dev/docs

Looks like the default value of the characters is undefined.
So something like (characters || []).map.. will help I think.
For deeper look at this you can debug useRequestData hook, as I can't see the source of that hook from you example

Related

React-How to display make objects loop in react

Here is what i tried
episode.js
import Parser from "rss-parser";
import React from "react";
export default function Episode() {
const parser = new Parser();
const url1 = "https://anchor.fm/s/75abc654/podcast/rss";
const [data, setData] = React.useState({});
(async () => {
let data = await parser.parseURL(url1);
setData(data);
// console.log(data.title)
// data.items.forEach((item) => {
// console.log(item.title)
//console.log(item.pubDate.slice(5, 17))
//console.log(item.enclosure.url)
// console.log(item.itunes.image)
});
})();
return(
<h1>{item.title}</h1>
{data.items.map((item, index)=>{
return(
<h1>{item.title}</h1>
)})}
)
}
And the output is blank screen.. No error in console.. Help me to get the data from the rss feed without blank screen
You're calling async method unlimited time! You need to call it once via useEffect just when component rendered for first time:
import Parser from "rss-parser";
import React, { useEffect } from "react";
function Episode() {
const parser = new Parser();
const url1 = "https://anchor.fm/s/75abc654/podcast/rss";
const [data, setData] = React.useState({});
useEffect(() => {
(async () => {
let data = await parser.parseURL(url1);
console.log(data);
setData(data);
})();
}, []);
return (
<>
{data.items?.map((item, index) => (
<h1>{item.title}</h1>
))}
</>
);
}
export default function App() {
return <Episode />;
}
Just replace your async function with a useEffect hook like this
useEffect(() => {
async function fetchMyAPI() {
let data = await parser.parseURL(url1);
setData(data);
// console.log(data.title)
// data.items.forEach((item) => {
// console.log(item.title)
//console.log(item.pubDate.slice(5, 17))
//console.log(item.enclosure.url)
// console.log(item.itunes.image)
}
fetchMyAPI();
}, []);
This will be executed once every time when your component is loaded on screen
Also change the data.item.map to
{data.items?.map((item, index) => {
return <h1>{item.title}</h1>;
})}
Else it will throw error on first render

API giving data in second render in React

I was trying to fetch api with react.js but on first render its gives nothing and the second render its gives data. This makes it so when I try to access the data later for an image I get an error, TypeError: Cannot read property 'news.article' of undefined, because it is initially empty. how can I solve this?
here is my code ..
import React, { useEffect, useState } from 'react';
const HomeContent = () => {
const [news, updateNews] = useState([]);
console.log(news);
useEffect(() => {
const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
fetch(api)
.then(response => response.json())
.then(data => updateNews(data))
.catch((error) => console.log(error))
}, [])
return (
<>
</>
);
};
export default HomeContent;
There is no issue with the code itself, the output you receive is expected. However, you can render the content after it is retrieved as such
import React, { useEffect, useState } from 'react';
const HomeContent = () => {
const [news, updateNews] = useState([]);
const [isLoading, setIsLoading] = useState(true);
console.log(news);
useEffect(() => {
const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
fetch(api)
.then(response => response.json())
.then(data => {
updateNews(data.articles);
setIsLoading(false);
})
.catch((error) => {
console.log(error);
setIsLoading(false);
})
}, [])
return (
<>
{isLoading ?
<p>Loading...</p> :
// Some JSX rendering the data
}
</>
);
};
export default HomeContent;

fetching random json getting first undefined then result

Beginner on reactjs here, trying to fetch random json, getting the result i want to get, but not the way i want it, for some reason it prints first 'undefined' then after that the result. Why cant i get just the result and without this '?'
my code:
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setThumbnail(json);
});
}, []);
console.log(thumbnail[0]?.thumbnailUrl);
return (
<div className="App">
<h1>Build</h1>
<p></p>
</div>
);
}
export default App;
console.log() inside App() directly will use the initial state of. thumbnail which is the empty, so it will show undefined.
To check the thumbnail, you should use another useEffect with adding a thumbnail dependency.
useEffect(() => {
if (thumbnail.length > 0) {
console.log(thumbnail[0].thumbnailUrl);
}
}, [thumbnail]);
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
const [isLoaded, setLoaded] = useState(false);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setLoaded(true);
setThumbnail(json);
});
}, []);
useEffect(() => {
if (isLoaded) {
console.log(thumbnail[0]?.thumbnailUrl);
}
}, [thumbnail]);
return (
<div className="App">
<h1>Build</h1>
<p></p>
</div>
);
}
export default App;
While the response of your http does not come, you can simply render a loading component (a text in this example), then when thumbnail state changes, React will re-render your component and update it with the new data.
Just a working example:
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [thumbnail, setThumbnail] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
setThumbnail(json);
})
.finally(() => {
setIsLoading(false);
});
}, []);
return (
<div className="App">
<h1>Build</h1>
{isLoading ? (
<h3>Loading...</h3>
) : (
thumbnail.map((item) => {
return <span key={item.id}>{item.title}</span>;
})
)}
</div>
);
}
export default App;

How to render a list from a JSON url? - ReactJS hooks

I want to render a list from a JSON URL. However, I have the following error: Objects are not valid as a React child (found: TypeError: Failed to fetch). If you meant to render a collection of children, use an array instead. What am I going wrong? Thanks for your answer
//hooks.tsx
import { useEffect, useState } from 'react'
export const useFetch = () => {
const [data, setData] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
useEffect(() => {
setLoading(true)
setError(null)
fetch('https://jsonkeeper.com/b/Z51B')
.then(res => res.json())
.then(json => {
setLoading(false)
if (json.data) {
setData(json.data)
} else {
setData([])
}
})
.catch(err => {
setError(err)
setLoading(false)
})
}, [])
return { data, loading, error }
}
//index.tsx
import React from 'react';
import { useFetch } from "./hooks.js";
import {CardItem} from './card';
export const List = () => {
const { data, loading, error } = useFetch()
if (loading) return <div>Loading...</div>
if (error) return <div>{error}</div>
return (
<>
<ul>
{data.map((item: any, index: any) => (
<li key={index}>
{item.names.map((name: any) => {
return <CardItem
family={item.family}
name={name}
/>
})
}
</li>
))}
</ul>
</>
);
};
I guess the problem is with your setError(err) in catch block of your custom hook. It should be setError(err.message).

How make work a search filter in react for node array

Hi guys i make a search filter in react for an array i get via my node server, but i got this error:
×
TypeError: props.filteredCharacters.map is not a function in components/CharacterList/index.js:6
Here the 2 files:
import React, { useEffect, useState } from 'react'
import SearchBox from '../SearchBox'
import CharacterList from '../CharacterList'
const SearchDisney = () => {
const [inputs, setInputs] = useState('');
const [btn, setBtn] = useState(false);
const [apiResponse, setApiResponse] = useState([]);
const [searchCharacter, setSearchCharacter] = useState('');
useEffect(() => {
callAPI();
if (inputs.length > 2) {
setBtn(true)
} else if (btn) {
setBtn(false)
}
}, [inputs, btn])
const callAPI = () => {
fetch("http://localhost:9000/disneyCharacter")
.then(res => res.json())
.then(res => setApiResponse(res))
}
const handleInput = (e) => {
setSearchCharacter(e.target.value)
}
const filteredCharacters = () => {
apiResponse.filter((character) => {
return character.name.toLowerCase().includes(searchCharacter.toLowerCase())
})
}
return (
<div className="search-container">
<h1>Personnage Infos</h1>
<SearchBox handleInput={handleInput} />
<CharacterList filteredCharacters={filteredCharacters} />
</div>
)
}
export default React.memo(SearchDisney)
And the CharacterList:
import React from 'react'
import Character from '../Character'
const CharacterList = (props) => {
const characters = props.filteredCharacters.map((character, id) => {
return <Character key={id} name={character.name} username={character.username} yearCreation={character.yearCreation}/>
})
return (
<div>
{ characters }
</div>
)
}
export default CharacterList
i can display the array in the first file but now i want to make search filter and got this error, any advice to get ride of this error?
Looks like there are 2 things you need to fix here:
on the SearchDisney component, you are not returning anything from the filteredCharacters function. Here is the fix:
const filteredCharacters = () => {
//need to return this
return apiResponse.filter((character) => {
return character.name.toLowerCase().includes(searchCharacter.toLowerCase())
})
}
Addtionally, in order for CharacterList to recieve the filteredCharacters prop as an array - you have to call the filteredCharacters function which returns this array, for example, like this:
<div className="search-container">
<h1>Personnage Infos</h1>
<SearchBox handleInput={handleInput} />
//call the function here:
<CharacterList filteredCharacters={filteredCharacters()} />
</div>

Categories

Resources