I am getting an error on my .map function. I believe the issue is greater than that though because sometimes my fetch comes back as undefined. I have been looking into solutions but haven't found anything that has given me a solution.
Props - is a logged-in user object that has the users ID
discBag consoles as an array sometimes but also will console as undefined. This is where I believe my issue is happening. I have looked into component mounting, but I was confused with the class and super() syntax.
here is the error I am getting along with the two console.logs
I am new to web development and this is my very first stack overflow question. Any solutions or guidance to the solution is greatly appreciated!
function DiscBag(props) {
const [loading, setLoading] = useState(true);
const [discBag, setDiscBag] = useState([]);
const userID = props.user.user.id;
console.log(userID)
console.log(discBag)
const getDiscs = async () => {
try {
const response = await fetch(`/users/${userID}`)
const data = await response.json()
setLoading(false)
setDiscBag(data.discBag)
} catch (error) {
console.log(error)
}
};
useEffect(() => {
getDiscs();
}, []);
if (loading) {
return <div> ....loading bro</div>;
}
return (
<div className="child">
<p>not loading</p>
{discBag.map((index, discs) => (
<div className="discs" key={index}>
{discs}
</div>
))}
</div>
);
}
CodePudding user response:
According to your description, it seems that there are times that the call to your server does not return a data.discBag
value, which causes the discBag
state to be empty (and the map
function can only run on arrays, here is the fix for the problem:
{discBag?.map((discs, index) => (
CodePudding user response:
Can you try with {discBag.map((discs, index) => ...
? first one is element, second one is the index like below;
array.map((currentElement, index) => { something... })