Search code examples
reactjsuse-effectadmin-bro

Items not loading in useEffect in react


This is my react component:

import { ApiClient } from 'admin-bro'
import { Box } from '@admin-bro/design-system'
import React, { useEffect, useState } from "react";
// import './gallery.css';

const api = new ApiClient()

const Gallery = () => {
  const [data, setData] = useState({})

  useEffect(() => {
    api.getPage({pageName: 'Gallery'}).then((response) => {
      setData(response.data)
    })
  }, [])
  console.log(data);
  console.log(data.imageNameArray);
  return (
    <section id="list-view">
      {data.imageNameArray && data.imageNameArray.map(name=>{
      <h3>Hello</h3>
      // <div className="card" style="width: 18rem;">
      //   <img className="card-img-top" src={"/images/"+name} alt="Card image cap"/>
      //   <div className="card-body">
      //     <h5 className="card-title">Name: {name}</h5>
      //     <h5 className="card-title">Size: 15kb</h5>
      //     <a href="#" classNamr="btn btn-danger">Delete</a>
      //   </div>
      // </div>
    })}
    </section>
  )
}

export default Gallery

My back-end:

Gallery: {
            label: "Gallery Images",
            handler: async (req, res, context)=>{
                const imageNameArray = await getImagesUrl();
                return {
                    imageNameArray: imageNameArray
                }
            },
            component: AdminBro.bundle('../views/admin/dashboard/gallery.jsx')
        },

I send data from back-end and console.log gives me the array I need but I am not getting anything in the html finally. I get the array on console. I have used async readdir with util.promisify and send the names of the files as an array. Can someone give me an insight on this.

Browser Console


Solution

  • The problem is you arrow function

      data.imageNameArray && data.imageNameArray.map(name=>{<h3>Hello</h3>})}
    

    doesn't return anything. Either remove {} or add return keyword.

    name => element is short for (name) => {return element;}, the way you have it, it is name => {element; return;}