Below is the component file SinglePostBySearch.js
import React, { useState } from 'react'
import Post from './Post'
const axios = require('axios')
const getElt=({loading},{isThereQuery},{posts})=>{
console.log(posts)
if(!loading && isThereQuery)
{
return(
<Post post={posts} id={posts.id} />
)
}
if(loading)
{
return <div>Loading</div>
}
if(!(loading && posts))
{
return <div>No post from the user</div>
}
}
function SinglePostBySearch(props) {
const [posts, setPosts] = useState({})
const [isThereQuery,setIsThereQuery]=useState(false)
const [loading,setIsLoading]=useState(false)
const fetchPost = (event) => {
const postId = event.target.value
if (postId) {
setIsThereQuery(false)
setIsLoading(true)
axios.get(`https://jsonplaceholder.typicode.com/posts/${postId}`).then(res => {
setPosts(res.data)
setIsThereQuery(true)
setIsLoading(false)
}).catch(err => {
console.log(err)
setIsLoading(false)
setPosts({})
})
}
else{
setPosts({})
setIsThereQuery(false)
}
}
return (
<div>
Hello {props.username}, enter a <strong>userId</strong> below
<input type="text" onChange={fetchPost} />
{getElt({loading},{isThereQuery},{posts})}
</div>
)
}
export default SinglePostBySearch
Problem/Question: Within the functional component's return, in the third line, I'm making a call to a another function getElt. It seems to be called around 4 or 5 times, which I figured from the console.log I inserted in the first line of the getElt function. I would like to know why it's being called so many times when it should be called just once.
I would like to point out that I do not have any console log statements in the child component Post that is being returned by the function getElt
getEltwill be called wheneverSinglePostBySearchgets rerendered - which will be whenever its props change. Its not uncommon for that to happen quite often, but we can't know for sure because you don't show any parent components which render it.