When I click the btn
, the onclick
function is suppose to pass the JSX from a another component, but calls the component 200+ times, and react breaks the operation and shows “React limits too many re-renders leading to an infinite loop”
then code
import React, { useState, useEffect } from "react";
import fetchAPI from "../../utils/fectch-api";
import SearchEl from "../../utils/searchel";
function Search() {
const [SearchResults, setSearchResults] = useState([]);
const [query, setQuery] = useState({ query: "" });
async function showdata() {
let data;
data = query.query ? await fetchAPI("hashtag_post", "hashtag", "love") : "";
console.log(data);
const dataObj = data.body.edge_hashtag_to_top_posts.edges.concat(
data.body.edge_hashtag_to_media.edges
);
const readableObj = dataObj.map((item) => {
return {
comments_disabled: item.node.comments_disabled,
Pic_dimensions: item.node.dimensions,
photo_url: item.node.display_url,
like_count: item.node.edge_liked_by,
caption: item.node.edge_media_to_caption,
comment_count: item.node.edge_media_to_comment,
user_id: item.node.id,
is_video: item.node.is_video,
posts_owner: item.node.owner,
post_shortcode: item.node.shortcode,
thumbnail_resources: item.node.thumbnail_resources,
};
});
setSearchResults(readableObj);
console.log(readableObj);
}
function handlequerychange(e) {
setQuery({ [e.target.name]: e.target.value });
}
const searchItems = SearchResults.map((item) => {
console.log(item);
return <SearchEl obj={item} />;
});
return (
<>
<div className="sticky top-0 bg-slate-800 rounded-xl flex items-center justify-between gap-2 px-1 mx-4 my-2">
<button
onClick={() => {
showdata();
}}
className="w-12 cursor-pointer aspect-square hover:rounded-[100%] hover:bg-slate-600"
>
<i className="fa-solid fa-magnifying-glass text-[1.2em"></i>
</button>
<input
className="w-[100%] text-lg outline-none border-0 bg-slate-800 py-1"
type="text"
name="query"
onChange={handlequerychange}
placeholder="Search"
/>
</div>
<div className="grid grid-cols-3 grid-row-[auto] overflow-y-scroll hide-scrollbar">
{searchItems}
</div>
</>
);
}
export default Search;
Initially, I am not using the query string because I need to test if it works or not. So please tell me where did the code got so many re-renders from … Thank you!
I was trying to create JSX elements for every object that came from the API but I showed too many references