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

Why I getting an error while trying to use map on data that i get using hook?

I trying map data which i get using custom hook that recives data from my "storage" (which is actually a class with array of objects and async function to get them) i reciving an error: Cannot read properties of undefined (reading ‘map’).
Code of hook:

const useCreations = () => {
  const service = new aboutPisanka();
  const [data, setData] = useState();

  useEffect(() => {
    console.log(123 )
    service.getAllCreations().then((data) => setData(data));
  }, []);

  return data
};

Code of element:

  const data = useCreations();
  console.log(data);
  const cards = data.map((data) => {
    const { heading, text, id, image } = data;
    return (
      <div key={id}>
        <img src={require(image)}/>
        <h1>{heading}</h1>
        <p>{text}</p>
      </div>
    );
  });

Code of function in class where data stores:

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

  getAllCreations = async () => {
    return this._creations;
  };

(Sorry for my bad english)

As I understand it happens because it maps data before it gets to state but I don’t have any idea how to fix it only making high order componen which will wrap my element.

>Solution :

I do not see your whole code however if you are receiving data in correct format after a while because of Api response,you can add ? in cards const cards = data?.map((data) => { to fix that error

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