JavaScript
x
76
76
1
//I fetched the data here using context Api
2
3
const [allProfiles, setAllProfiles] = useState("");
4
const fetchAllProfiles = async () => {
5
const res = await axios.get("http://localhost:5000/api/all-profiles");
6
setAllProfiles(res.data);
7
};
8
9
//I receive the data here in the frontend.
10
11
import Image from "next/image";
12
import React, { useContext, useEffect } from "react";
13
import Layout from "@/components/Layout";
14
import MyContext from "@/store/MyContext";
15
16
function Sellers() {
17
const { allProfiles, fetchAllProfiles } = useContext(MyContext);
18
19
useEffect(() => {
20
fetchAllProfiles();
21
}, []);
22
23
return (
24
<Layout>
25
<div className="container flex justify-center mx-auto pt-16">
26
<div>
27
<p className="text-gray-500 text-lg text-center font-normal pb-3">
28
SELLERS
29
</p>
30
31
<h1 className="thesellermaintext">
32
View Buyers Profile Here, You Might Be Lucky To Find Your Dream Car
33
Too.
34
</h1>
35
</div>
36
</div>
37
{allProfiles.map((profiles, i) => (
38
<div className="w-full bg-gray-100 px-10 pt-10">
39
<div className="container mx-auto">
40
<div className="thesellerbg">
41
<div className="sellersimagebg">
42
<div className="rounded overflow-hidden shadow-md bg-white">
43
<div className="absolute -mt-20 w-full flex justify-center">
44
<div className="h-32 w-32">
45
<Image
46
width={400}
47
height={400}
48
src="/assets/images/d17.jpg"
49
alt="profile"
50
className="sellersimage"
51
/>
52
</div>
53
</div>
54
<div className="px-6 mb-8 mt-16">
55
<div className="font-bold text-3xl text-center pb-1">
56
{allProfiles.name}
57
</div>
58
<p className="text-gray-800 text-sm text-center">
59
{profiles.businessStatus}
60
</p>
61
<p className="text-center text-gray-600 text-base pt-3 font-normal">
62
{profiles.description}
63
</p>
64
</div>
65
</div>
66
</div>
67
</div>
68
</div>
69
</div>
70
))}
71
</Layout>
72
);
73
}
74
75
export default Sellers;
76
The problem I’m facing here was, whenever I fetch the data with a button click (the button that leads to this route), the data will be fetch successfully, but whenever I input the link address directly myself in the browser, It keeps returning empty string when i console.log the data (Like this <empty string>
), and keep throwing error saying “allCars.map is not a function.
Advertisement
Answer
you try initialing “allProfiles” with empty array like this:
JavaScript
1
2
1
const [allProfiles, setAllProfiles] = useState([]);
2
empty string seem tobe different from an Array come from api response