0

What is the best way to set a new filteredImages array with useState?

I notice I’m doing return attachments.filter(attachment => { … twice, so wondered if I can do it once.

  const [filteredImages, setFilteredImages] = useState(() => {
    return attachments.filter(attachment => {
      const {name, isImage} = attachment;
      if (name) {
        const newFileFormat = name.split('.').slice(-1)[0];
        return isImage && newFileFormat !== 'tiff';
      }
    });
  });

…

  useEffect(() => {
    setFilteredImages(() => {
      return attachments.filter(attachment => {
        const {name, isImage} = attachment;
        if (name) {
          const newFileFormat = name.split('.').slice(-1)[0];
          return isImage && newFileFormat !== 'tiff';
        }
      });
    });
  }, [attachments, card.attachments]);

I passes an argument to setFilteredImages to set a new filteredImages array but it didn’t work.

Happy1234
  • 537
  • 3
  • 15

0 Answers0