Reputation: 33
I have React code which fetch from my Api posts and displays it.
when I tried to display the posts with map
, I used useState
inside the map
and I got this error:
Error: Rendered more hooks than during the previous render.
When I deleted the useState it worked.
This is my code
import {useState,useContext,useEffect} from "react"
import {username} from "./username"
const PostDisplay = (post) => {
const [try, setTry] = useState("")
return (
<div>Hello</div>
);
}
function Home(){
const [loggedIn,setLoggedIn] = useContext(username)
const [posts, setPosts] = useState([])
useEffect(() => {
fetch("/posts")
.then((response) => response.json())
.then((data) => {
setPosts(data)
console.log(data)
})
}, [])
if(loggedIn){
return (
<div align="center">
<br/>
<br/>
<div>
{posts.map(PostDisplay)}
</div>
</div>
)
}
else{
return (
<div>
<h1 align="center">You are not logged in!</h1>
</div>
)
}
}
export default Home
please help me.
Upvotes: 0
Views: 761
Reputation: 1568
You cannot assign a React component like that inside a map
{posts.map((post) => <PostDisplay post={post}/>)}
iterate through the array and pass the value as prop to the component.
const PostDisplay = ({post}) => {
const [try, setTry] = useState("")
return (
<div>Hello </div>
);
}
Upvotes: 3