Search code examples
next.jsstrapinuxt-strapi

Unable to fetch image from strapi and getting this error " http://localhost:1337/undefined"


I am working on a MERN stack e-commerce website. Currently, I'm working with Strapi as the backend. One issue I've encountered is that images aren't rendering as expected on the frontend, and the console returns http://localhost:1337/undefined for the URLs of images.

enter image description here

Here is the data of that api enter image description here

This is my .env.local file ...it is in the root directory

NEXT_PUBLIC_BACKEND_BASE_URL='http://localhost:1337/'

This is my Header.jsx file .

function Header() {

const [categoryList, setCategoryList] = useState([]);

useEffect(() => {
    getCategoryList();
}, [])

// Get getCategoryList
const getCategoryList = () => {
    GlobalApi.getCategory().then(resp => {

        console.log("CategoryList Response:", resp.data.data);
        setCategoryList(resp.data.data);
    })
}

return (
                <DropdownMenuContent>
                    <DropdownMenuLabel>Browse Category</DropdownMenuLabel>

                    <DropdownMenuSeparator />
                    {categoryList.map((category, index) => (
                        <DropdownMenuItem key={index}>

   {console.log(`here is the result `+ process.env.NEXT_PUBLIC_BACKEND_BASE_URL + category?.icon?.url)}
                            <Image src={
                                process.env.NEXT_PUBLIC_BACKEND_BASE_URL +
                                category.icon.url}
                                unoptimized={true}

                                alt="logo"
                                width={20}
                                height={20} />
                                

                            <h2>{category?.name}</h2>
                        </DropdownMenuItem>
                    ))}


                </DropdownMenuContent>
            </DropdownMenu>



export default Header

The problem may be with image URL construction as when I do a log URL, it results in http://localhost:1337/undefined, which must mean category.icon.url is being undefined or doesn't have any proper structure defined.

Here are the things which I have tested so far,

The .env file got loaded correctly while logging process.env.NEXT_PUBLIC_BACK.

Despite these checks, the image URL is still broken. Any insights or suggestions on how to resolve this issue would be greatly appreciated!


Solution

  • process.env.NEXT_PUBLIC_BACKEND_BASE_URL + category.icon.url
    

    This not going to work, because your icon is array

    enter image description here

    instead you should use:

    process.env.NEXT_PUBLIC_BACKEND_BASE_URL + category.icon[0].url