Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having troubles with the .map funciton

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
}

>Solution :

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) => (
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading