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();
  const cards = data.map((data) => {
    const { heading, text, id, image } = data;
    return (
      <div key={id}>
        <img src={require(image)}/>

Code of function in class where data stores:

  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

Leave a Reply