I created a home page that contains three components HomeHeader
, CompanyList
and ScrollToTopBtn
.
Focusing on CompanyList
it is a container component that shows list of CompanyCards
that were fetched using an API in Home
page. List of companies are initialized in Home
page like this
const [companies, setCompanies] = useState([]);
The problem is that initially after making the API call, I use spread operator to update the companies
list like this
setCompanies(prevCompanies=>{return [...prevCompanies, fetchedCompanies]});
But an error occurs since I believe that there is an empty element in index 0
. companies
list must has looked like this ['','Facebrog','Binterest']
for example.
I tried to use another approach by using concat
method but companies
list stayed empty and showed no companies found
message.
Below is the source code for Home
page
const Home = () => {
const [page, setPage] = useState(1); //In order to avoid showing "no companies found" initially
const [isLoading, setIsLoading] = useState(true);
const [companies, setCompanies] = useState([]);
const [isError, setIsError] = useState(false);
const [hasMore, setHasMore] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
setIsError(false);
try {
const fetchedCompanies = await fetchFeedData(page);
setCompanies((prevCompanies=>{prevCompanies.concat(fetchedCompanies)})); //problem here
setHasMore(fetchedCompanies.length > 0)
} catch (e) {
setIsError(true)
setHasMore(false);
}
setIsLoading(false)
}
fetchData();
}, [page])
return (
<div>
<ScrollToTopBtn />
<Helmet>
<title>{stackinfo.title} - {home.title}</title>
</Helmet>
<HomeHeader />
{
isLoading ? (<LoadingSpinner />) :
isError ? (<ErrorBoundary message={somethingWrongError.message}></ErrorBoundary>) :
<CompanyList companies={companies} ></CompanyList>
}
<Container className={"mt-5"}>
<Row>
<Col sm={12}>
{(!isLoading && !isError && hasMore) &&
<CustomBtn
ButtonText={showMoreBtnText.message}
onClick={() => { console.log("Need to increment number of pages") }}
></CustomBtn>}
</Col>
</Row>
</Container>
</div>
)
}
I tried to check the fetchedCompanies
and companies
after making the API call
const fetchedCompanies = await fetchFeedData(page);
//Returning new array containing previous companies and recent fetchedCompanies
console.log(fetchedCompanies);
setCompanies((prevCompanies=>{prevCompanies.concat(fetchedCompanies)}));
console.log(companies);
fetchedCompanies
logged an array that has 9 elements, while companies
as mentioned above logged empty array []
.
Sorry if I missed something, I am still new to React.