kandi background
Explore Kits

heroicons | free MIT-licensed high | Icon library

 by   tailwindlabs JavaScript Version: v1.0.6 License: MIT

 by   tailwindlabs JavaScript Version: v1.0.6 License: MIT

Download this library from

kandi X-RAY | heroicons Summary

heroicons is a JavaScript library typically used in User Interface, Icon, React applications. heroicons has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
A set of 450+ free MIT-licensed high-quality SVG icons for you to use in your web projects. Available as basic SVG icons and via first-party React and Vue libraries.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • heroicons has a medium active ecosystem.
  • It has 14454 star(s) with 897 fork(s). There are 165 watchers for this library.
  • There were 2 major release(s) in the last 12 months.
  • There are 0 open issues and 308 have been closed. On average issues are closed in 227 days. There are 1 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of heroicons is v1.0.6
heroicons Support
Best in #Icon
Average in #Icon
heroicons Support
Best in #Icon
Average in #Icon

quality kandi Quality

  • heroicons has 0 bugs and 0 code smells.
heroicons Quality
Best in #Icon
Average in #Icon
heroicons Quality
Best in #Icon
Average in #Icon

securitySecurity

  • heroicons has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • heroicons code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
heroicons Security
Best in #Icon
Average in #Icon
heroicons Security
Best in #Icon
Average in #Icon

license License

  • heroicons is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
heroicons License
Best in #Icon
Average in #Icon
heroicons License
Best in #Icon
Average in #Icon

buildReuse

  • heroicons releases are available to install and integrate.
  • Installation instructions are not available. Examples and code snippets are available.
heroicons Reuse
Best in #Icon
Average in #Icon
heroicons Reuse
Best in #Icon
Average in #Icon
Top functions reviewed by kandi - BETA

kandi has reviewed heroicons and discovered the below as its top functions. This is intended to give you an instant insight into heroicons implemented functionality, and help decide if they suit your requirements.

  • Build icons .
  • Main main function .
  • Read the icons for a given style
  • Export all the icons
  • Ensures a file exists
  • Ensure a JSON file .

heroicons Key Features

A set of free MIT-licensed high-quality SVG icons for UI development.

Basic Usage

copy iconCopydownload iconDownload
<svg class="h-6 w-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
  <path
    stroke-linecap="round"
    stroke-linejoin="round"
    stroke-width="2"
    d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
  />
</svg>

React

copy iconCopydownload iconDownload
npm install @heroicons/react

Vue

copy iconCopydownload iconDownload
npm install @heroicons/vue

How to prevent set state before useEffect?

copy iconCopydownload iconDownload
 useEffect(() => {
    const fetchData = async () => {
      try {
        const videos = await listAll(reference);
        const completeVideos = await Promise.all(
          videos.items.map(async (video) => {
            const metadata = await getMetadata(ref(storage, video.fullPath));
            const url = await getDownloadURL(ref(storage, video.fullPath));
            return {
              name: metadata.name,
              size: prettysize(metadata.size),
              url,
            };
          })
        );
        setVideos(completeVideos);
      } catch (e) {
        console.log(e);
      }
    };
    fetchData();
  }, []);

Infinity loop when I try to get information from firebase into nextjs using useEffect

copy iconCopydownload iconDownload
useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos); //update `videos` again --> call `useEffect` again due to `videos` update
      });
    }

    exec();
  }, [reference, videos]); //`videos` dependency 
useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

    exec();
  }, [reference]);
-----------------------
useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos); //update `videos` again --> call `useEffect` again due to `videos` update
      });
    }

    exec();
  }, [reference, videos]); //`videos` dependency 
useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

    exec();
  }, [reference]);

Javascript const object syntax - what is this doing? (using in a Vue script)

copy iconCopydownload iconDownload
window.MyApp = {
  app: null,
  icons: {
    SearchIcon : 'Hello!'
  },
};

const { SearchIcon } = window.MyApp.icons;

console.log(SearchIcon);

How does the heroicons codebase make use of [xx] in a pip install heroicons[django] or heroicons[jinja]?

copy iconCopydownload iconDownload
[options.extras_require]
django =
    django >= 2.2
jinja =
    jinja2 >= 2.8

Webpack/Vue vue__WEBPACK_IMPORTED_MODULE... is not defined

copy iconCopydownload iconDownload
import Vue from 'vue'
import { createApp } from 'vue'
const app = createApp({})
-----------------------
import Vue from 'vue'
import { createApp } from 'vue'
const app = createApp({})

Button Function Not calling From Another file in React

copy iconCopydownload iconDownload
import { useState } from 'react'

export default function CustomerDashboard() {
  // I am not sure why you want to keep notice in state,
  // because in your example you did not call setNotice
  const [notice, setNotice] = useState(`
    Customer Notice: Optimism Is Invaluable For The Meaningful Life.
    With A Firm Belief In A Positive Future You Can Throw Yourself Into The Service
    Of That Which Is Larger Than You Are. -Martin Seligman
  `)
  const [isNoticeVisible, setIsNoticeVisible] = useState(true)

  return (
    <div>
      <h1>My Account - Dashboard Overview</h1>

      {isNoticeVisible && (
        <CustomerNotice
          notice={notice}
          setIsNoticeVisible={setIsNoticeVisible}
        />
      )}
    </div>
  )
}

function CustomerNotice(props) {
  const { notice, setIsNoticeVisible } = props
  const [isTruncated, setIsTruncated] = useState(true)

  function toggleIsTruncated() {
    setIsTruncated(!isTruncated)
  }

  return (
    <div>
      <Read text={notice} isTruncated={isTruncated} />

      <button onClick={toggleIsTruncated}>
        {isTruncated ? 'Read More' : 'Read Less'}
      </button>

      <button onClick={() => setIsNoticeVisible(false)}>Dismiss</button>
    </div>
  )
}

function Read(props) {
  const { text, isTruncated } = props
  const result = isTruncated ? text.slice(0, 90) : text

  return <div>{result}....</div>
}
const { text, isTruncated } = props
-----------------------
import { useState } from 'react'

export default function CustomerDashboard() {
  // I am not sure why you want to keep notice in state,
  // because in your example you did not call setNotice
  const [notice, setNotice] = useState(`
    Customer Notice: Optimism Is Invaluable For The Meaningful Life.
    With A Firm Belief In A Positive Future You Can Throw Yourself Into The Service
    Of That Which Is Larger Than You Are. -Martin Seligman
  `)
  const [isNoticeVisible, setIsNoticeVisible] = useState(true)

  return (
    <div>
      <h1>My Account - Dashboard Overview</h1>

      {isNoticeVisible && (
        <CustomerNotice
          notice={notice}
          setIsNoticeVisible={setIsNoticeVisible}
        />
      )}
    </div>
  )
}

function CustomerNotice(props) {
  const { notice, setIsNoticeVisible } = props
  const [isTruncated, setIsTruncated] = useState(true)

  function toggleIsTruncated() {
    setIsTruncated(!isTruncated)
  }

  return (
    <div>
      <Read text={notice} isTruncated={isTruncated} />

      <button onClick={toggleIsTruncated}>
        {isTruncated ? 'Read More' : 'Read Less'}
      </button>

      <button onClick={() => setIsNoticeVisible(false)}>Dismiss</button>
    </div>
  )
}

function Read(props) {
  const { text, isTruncated } = props
  const result = isTruncated ? text.slice(0, 90) : text

  return <div>{result}....</div>
}
const { text, isTruncated } = props

TailwindCSS fade in Element on click

copy iconCopydownload iconDownload
`transition-all duration-200 ${fade ? "opacity-100" : "opacity-0"}`

function Header() {
  const [popCard, setPopCard] = useState("hidden");
  const [fade, setFade] = useState(false);

  const handleMenuClick = () => {
    setPopCard("inline-block");
    setFade(true);
  };

  const handleXClick = () => {
    setPopCard("hidden");
    setFade(false);
  };

  console.log(fade, "fade");

  return (
    <div className="text-center">
      <header className="sticky z-50 top-0  shadow-md bg-white border-b p-5">
        <div className="flex justify-between items-center">
          <h1 className="text-6xl text-red-500 cursor-pointer">Velvet</h1>
          <button
            className="text-3xl border rounded-lg px-5"
            onClick={handleMenuClick}
          >
            Menu
          </button>
        </div>
      </header>

      <div className="p-10">
        <div
          className={`transition-all duration-200    ${
            fade ? "opacity-100" : "opacity-0"
          }`}
        >
          <div className="flex justify-end">
            <button className="mt-2 mr-2 border p-2" onClick={handleXClick}>
              Close
            </button>
          </div>
          <div className="space-y-2 text-3xl text-center mt-5 mb-10 mx-5 text-red-500">
            <h1>Kontakt</h1>
            <h1>O Velvetu</h1>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Header;

-----------------------
`transition-all duration-200 ${fade ? "opacity-100" : "opacity-0"}`

function Header() {
  const [popCard, setPopCard] = useState("hidden");
  const [fade, setFade] = useState(false);

  const handleMenuClick = () => {
    setPopCard("inline-block");
    setFade(true);
  };

  const handleXClick = () => {
    setPopCard("hidden");
    setFade(false);
  };

  console.log(fade, "fade");

  return (
    <div className="text-center">
      <header className="sticky z-50 top-0  shadow-md bg-white border-b p-5">
        <div className="flex justify-between items-center">
          <h1 className="text-6xl text-red-500 cursor-pointer">Velvet</h1>
          <button
            className="text-3xl border rounded-lg px-5"
            onClick={handleMenuClick}
          >
            Menu
          </button>
        </div>
      </header>

      <div className="p-10">
        <div
          className={`transition-all duration-200    ${
            fade ? "opacity-100" : "opacity-0"
          }`}
        >
          <div className="flex justify-end">
            <button className="mt-2 mr-2 border p-2" onClick={handleXClick}>
              Close
            </button>
          </div>
          <div className="space-y-2 text-3xl text-center mt-5 mb-10 mx-5 text-red-500">
            <h1>Kontakt</h1>
            <h1>O Velvetu</h1>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Header;

TypeError: Cannot read properties of undefined (reading 'user')

copy iconCopydownload iconDownload
<Image
    onClick={signOut}
    className="rounded-full cursour-pointer"
    src={session?.user?.image}
    width="40"
    height="40"
    layout="fixed"
/>
-----------------------
  const { data: session } = useSession();

Headless UI Dropdown - Open menu above the button

copy iconCopydownload iconDownload
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


import { Menu, Transition } from '@headlessui/react'
import { Fragment, useEffect, useRef, useState } from 'react'
import { ChevronDownIcon } from '@heroicons/react/solid'

export default function Example() {
    return (
       
            <div className="w-56 text-right fixed top-16">
                <Menu as="div" className="relative inline-block text-left">
                    <div>
                        <Menu.Button className="inline-flex justify-center w-full px-4 py-2 text-sm font-medium text-white bg-black rounded-md bg-opacity-20 hover:bg-opacity-30 focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75">
                            Options
                            <ChevronDownIcon
                                className="w-5 h-5 ml-2 -mr-1 text-violet-200 hover:text-violet-100"
                                aria-hidden="true"
                            />
                        </Menu.Button>
                    </div>
                    <Transition
                        as={Fragment}
                        enter="transition ease-out duration-100"
                        enterFrom="transform opacity-0 scale-95"
                        enterTo="transform opacity-100 scale-100"
                        leave="transition ease-in duration-75"
                        leaveFrom="transform opacity-100 scale-100"
                        leaveTo="transform opacity-0 scale-95"
                    >
                        <Menu.Items className="-top-2 transform -translate-y-full absolute right-0 w-56 origin-top-right bg-white divide-y divide-gray-100 rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                            <div className="px-1 py-1 ">
                                <Menu.Item>
                                    {({ active }) => (
                                        <button
                                            className={`${active ? 'bg-violet-500 text-white' : 'text-gray-900'
                                                } group flex rounded-md items-center w-full px-2 py-2 text-sm`}
                                        >
                                            {active ? (
                                                <EditActiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            ) : (
                                                <EditInactiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            )}
                                            Edit
                                        </button>
                                    )}
                                </Menu.Item>
                                <Menu.Item>
                                    {({ active }) => (
                                        <button
                                            className={`${active ? 'bg-violet-500 text-white' : 'text-gray-900'
                                                } group flex rounded-md items-center w-full px-2 py-2 text-sm`}
                                        >
                                            {active ? (
                                                <DuplicateActiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            ) : (
                                                <DuplicateInactiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            )}
                                            Duplicate
                                        </button>
                                    )}
                                </Menu.Item>
                            </div>
                            <div className="px-1 py-1">
                                <Menu.Item>
                                    {({ active }) => (
                                        <button
                                            className={`${active ? 'bg-violet-500 text-white' : 'text-gray-900'
                                                } group flex rounded-md items-center w-full px-2 py-2 text-sm`}
                                        >
                                            {active ? (
                                                <ArchiveActiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            ) : (
                                                <ArchiveInactiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            )}
                                            Archive
                                        </button>
                                    )}
                                </Menu.Item>
                                <Menu.Item>
                                    {({ active }) => (
                                        <button
                                            className={`${active ? 'bg-violet-500 text-white' : 'text-gray-900'
                                                } group flex rounded-md items-center w-full px-2 py-2 text-sm`}
                                        >
                                            {active ? (
                                                <MoveActiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            ) : (
                                                <MoveInactiveIcon
                                                    className="w-5 h-5 mr-2"
                                                    aria-hidden="true"
                                                />
                                            )}
                                            Move
                                        </button>
                                    )}
                                </Menu.Item>
                            </div>
                            <div className="px-1 py-1">
                                <Menu.Item>
                                    {({ active }) => (
                                        <button
                                            className={`${active ? 'bg-violet-500 text-white' : 'text-gray-900'
                                                } group flex rounded-md items-center w-full px-2 py-2 text-sm`}
                                        >
                                            {active ? (
                                                <DeleteActiveIcon
                                                    className="w-5 h-5 mr-2 text-violet-400"
                                                    aria-hidden="true"
                                                />
                                            ) : (
                                                <DeleteInactiveIcon
                                                    className="w-5 h-5 mr-2 text-violet-400"
                                                    aria-hidden="true"
                                                />
                                            )}
                                            Delete
                                        </button>
                                    )}
                                </Menu.Item>
                            </div>
                        </Menu.Items>
                    </Transition>
                </Menu>
            </div>
     

    )
}

function EditInactiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <path
                d="M4 13V16H7L16 7L13 4L4 13Z"
                fill="#EDE9FE"
                stroke="#A78BFA"
                strokeWidth="2"
            />
        </svg>
    )
}

function EditActiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <path
                d="M4 13V16H7L16 7L13 4L4 13Z"
                fill="#8B5CF6"
                stroke="#C4B5FD"
                strokeWidth="2"
            />
        </svg>
    )
}

function DuplicateInactiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <path
                d="M4 4H12V12H4V4Z"
                fill="#EDE9FE"
                stroke="#A78BFA"
                strokeWidth="2"
            />
            <path
                d="M8 8H16V16H8V8Z"
                fill="#EDE9FE"
                stroke="#A78BFA"
                strokeWidth="2"
            />
        </svg>
    )
}

function DuplicateActiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <path
                d="M4 4H12V12H4V4Z"
                fill="#8B5CF6"
                stroke="#C4B5FD"
                strokeWidth="2"
            />
            <path
                d="M8 8H16V16H8V8Z"
                fill="#8B5CF6"
                stroke="#C4B5FD"
                strokeWidth="2"
            />
        </svg>
    )
}

function ArchiveInactiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <rect
                x="5"
                y="8"
                width="10"
                height="8"
                fill="#EDE9FE"
                stroke="#A78BFA"
                strokeWidth="2"
            />
            <rect
                x="4"
                y="4"
                width="12"
                height="4"
                fill="#EDE9FE"
                stroke="#A78BFA"
                strokeWidth="2"
            />
            <path d="M8 12H12" stroke="#A78BFA" strokeWidth="2" />
        </svg>
    )
}

function ArchiveActiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <rect
                x="5"
                y="8"
                width="10"
                height="8"
                fill="#8B5CF6"
                stroke="#C4B5FD"
                strokeWidth="2"
            />
            <rect
                x="4"
                y="4"
                width="12"
                height="4"
                fill="#8B5CF6"
                stroke="#C4B5FD"
                strokeWidth="2"
            />
            <path d="M8 12H12" stroke="#A78BFA" strokeWidth="2" />
        </svg>
    )
}

function MoveInactiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <path d="M10 4H16V10" stroke="#A78BFA" strokeWidth="2" />
            <path d="M16 4L8 12" stroke="#A78BFA" strokeWidth="2" />
            <path d="M8 6H4V16H14V12" stroke="#A78BFA" strokeWidth="2" />
        </svg>
    )
}

function MoveActiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <path d="M10 4H16V10" stroke="#C4B5FD" strokeWidth="2" />
            <path d="M16 4L8 12" stroke="#C4B5FD" strokeWidth="2" />
            <path d="M8 6H4V16H14V12" stroke="#C4B5FD" strokeWidth="2" />
        </svg>
    )
}

function DeleteInactiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <rect
                x="5"
                y="6"
                width="10"
                height="10"
                fill="#EDE9FE"
                stroke="#A78BFA"
                strokeWidth="2"
            />
            <path d="M3 6H17" stroke="#A78BFA" strokeWidth="2" />
            <path d="M8 6V4H12V6" stroke="#A78BFA" strokeWidth="2" />
        </svg>
    )
}

function DeleteActiveIcon(props) {
    return (
        <svg
            {...props}
            viewBox="0 0 20 20"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
        >
            <rect
                x="5"
                y="6"
                width="10"
                height="10"
                fill="#8B5CF6"
                stroke="#C4B5FD"
                strokeWidth="2"
            />
            <path d="M3 6H17" stroke="#C4B5FD" strokeWidth="2" />
            <path d="M8 6V4H12V6" stroke="#C4B5FD" strokeWidth="2" />
        </svg>
    )
}

what is the best way to use react router V6 navigation with redux and redux thunk actions?

copy iconCopydownload iconDownload
// register.js or useRegister.js

export const useRegisterUser = () => {

  const navigate = useNavigate();

  const doRegister = (credentials) => {
    return apiActionCreators.apiCallBegan({
    url,
    method: 'post',
    data: credentials,
    onStart: START_LOADING.type,
    onEnd: END_LOADING.type,
    onSuccessFunc: (data) => (dispatch, store) => {
      dispatch(USER_REGISTERED(data))
      dispatch(CLEAR_MAIN_ERROR())
      // allowed since it's inside a hook
      navigate("menu")
    },
    onErrorFunc: (error) => (dispatch, store) => {
      dispatch(ADD_MAIN_ERROR(error))
    },
  })
}

return {
    doRegister 
}

}
// registerPage.js

import { useRegisterUser } from './register.js'
// other imports 

const RegisterForm = (props) => {

  const { doRegister } = useRegisterUser()

// other stuffs
// grab credentials

    dispatch(doRegister(credentials))

// other stuffs

return (<></>)
}
-----------------------
// register.js or useRegister.js

export const useRegisterUser = () => {

  const navigate = useNavigate();

  const doRegister = (credentials) => {
    return apiActionCreators.apiCallBegan({
    url,
    method: 'post',
    data: credentials,
    onStart: START_LOADING.type,
    onEnd: END_LOADING.type,
    onSuccessFunc: (data) => (dispatch, store) => {
      dispatch(USER_REGISTERED(data))
      dispatch(CLEAR_MAIN_ERROR())
      // allowed since it's inside a hook
      navigate("menu")
    },
    onErrorFunc: (error) => (dispatch, store) => {
      dispatch(ADD_MAIN_ERROR(error))
    },
  })
}

return {
    doRegister 
}

}
// registerPage.js

import { useRegisterUser } from './register.js'
// other imports 

const RegisterForm = (props) => {

  const { doRegister } = useRegisterUser()

// other stuffs
// grab credentials

    dispatch(doRegister(credentials))

// other stuffs

return (<></>)
}

Community Discussions

Trending Discussions on heroicons
  • How to prevent set state before useEffect?
  • Infinity loop when I try to get information from firebase into nextjs using useEffect
  • Javascript const object syntax - what is this doing? (using in a Vue script)
  • How does the heroicons codebase make use of [xx] in a pip install heroicons[django] or heroicons[jinja]?
  • Webpack/Vue vue__WEBPACK_IMPORTED_MODULE... is not defined
  • Button Function Not calling From Another file in React
  • TailwindCSS fade in Element on click
  • TypeError: Cannot read properties of undefined (reading 'user')
  • Headless UI Dropdown - Open menu above the button
  • what is the best way to use react router V6 navigation with redux and redux thunk actions?
Trending Discussions on heroicons

QUESTION

How to prevent set state before useEffect?

Asked 2022-Apr-16 at 20:29

I have a React/Next component. This component download data from firebase storage based on a route. For example, for route http://localhost:3000/training/javascript the component with get data from /training/javascript router in firebase storage.

// ReactJS
import { useState, useEffect } from "react";

// NextJS
import { useRouter } from "next/router";

// Seo
import Seo from "../../../components/Seo";

// Hooks
import { withProtected } from "../../../hook/route";

// Components
import DashboardLayout from "../../../layouts/Dashboard";

// Firebase
import { getDownloadURL, getMetadata, listAll, ref } from "firebase/storage";
import { storage } from "../../../config/firebase";

// Utils
import prettysize from "prettysize";
import capitalize from "../../../utils/capitalize";
import { PlayIcon } from "@heroicons/react/outline";
import { async } from "@firebase/util";

function Video() {
  // States
  const [videos, setVideos] = useState([]);

  // Routing
  const router = useRouter();
  const { id } = router.query;

  // Reference
  const reference = ref(storage, `training/${id}`);

  useEffect(() => {
    const fetchData = async () => {
      let tempVideos = [];
      let completeVideos = [];
      const videos = await listAll(reference);

      videos.items.forEach((video) => {
        tempVideos.push(video);
      });

      tempVideos.forEach((video) => {
        getMetadata(ref(storage, video.fullPath)).then((metadata) => {
          completeVideos.push({
            name: metadata.name,
            size: prettysize(metadata.size),
          });
        });
      });

      tempVideos.forEach((video) => {
        getDownloadURL(ref(storage, video.fullPath)).then((url) => {
          completeVideos.forEach((completeVideo) => {
            if (completeVideo.name === video.name) {
              completeVideo.url = url;
            }
          });
        });
      });

      setVideos(completeVideos);
    };

    fetchData();
  }, [id]);

  console.log("Render", videos)
  return (
    <>
      <Seo
        title={`${capitalize(id)} Training - Dashboard`}
        description={`${capitalize(
          id
        )} training for all Every Benefits Agents.`}
      />
      <DashboardLayout>
        <h2>{capitalize(reference.name)}</h2>
        <ul>
          {videos.map((video) => {
            return (
              <li key={video.name}>
                <a href={video.url} target="_blank" rel="noopener noreferrer">
                  <PlayIcon />
                  {video.name}
                </a>
                <span>{video.size}</span>
              </li>
            );
          })}
        </ul>
      </DashboardLayout>
    </>
  );
}

export default withProtected(Video);

I have an useState that should be the array of videos from firebase. I use an useEffect to get the data from firebase and extract the needed information. Some medatada and the url.

Everything's fine. The information is extracted, and is updated to the state correctly. But when the state is updated, it's no showings on the screen.

This is a console.log of the videos state updated, so you can see it's correctly updated. enter image description here

ANSWER

Answered 2022-Apr-16 at 20:29

You messed up a bit with asynchronous code and loops, this should work for you:

 useEffect(() => {
    const fetchData = async () => {
      try {
        const videos = await listAll(reference);
        const completeVideos = await Promise.all(
          videos.items.map(async (video) => {
            const metadata = await getMetadata(ref(storage, video.fullPath));
            const url = await getDownloadURL(ref(storage, video.fullPath));
            return {
              name: metadata.name,
              size: prettysize(metadata.size),
              url,
            };
          })
        );
        setVideos(completeVideos);
      } catch (e) {
        console.log(e);
      }
    };
    fetchData();
  }, []);

Promise.all takes an array of promises, and returns a promise that resolves with an array of all the resolved values once all the promises are in the fulfilled state. This is useful when you want to perform asynchronous operations like your getMetaData and getDownloadURL, on multiple elements of an array. You will use .map instead of .forEach since map returns an array, while forEach does not. By passing an async function to .map, since an async function always returns a Promise, you are basically creating an array of promises. and that's what you can feed Promise.all with. That's it, now it just waits that all the async calls are done and you can just await for Promise.all to resolve.

Source https://stackoverflow.com/questions/71896764

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install heroicons

You can download it from GitHub.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.