0

If I use a string literal in the require it works fine, if I use a string variable it errors with: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

This is my code:

type FlagIconProps = {
    twoCharLocationCode: string,
    widthPx?: string
}

const FlagIcon = ({ twoCharLocationCode, widthPx = '32px' }: FlagIconProps) => {

    const fileName2 = './us.svg'

    // hard coded filename WORKS
    // const flagIconImg: string = require('./us.svg').default

    // using a variable in the require casues: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    const flagIconImg: string = require(fileName2).default

    return (
        <img
            src={flagIconImg}
            className="flag-icon"
            alt="flag-icon"
            width={widthPx}
        />
    )
}

export default FlagIcon

But I'm not using useEffect anywhere in the app so I really don't understand what to do to fix this. Using variables is fairly fundamental to coding lol

Appreciate any help!

Force Hero
  • 2,674
  • 3
  • 19
  • 35
  • 1
    I don't believe this is a React issue. "Since Webpack is running in build-time, it can't figure out which modules to bundle when the name is a dynamic variable. You can give it hints by specifying part of the path (for example, if you know all the modules are in a single directory)." https://stackoverflow.com/questions/37241662/using-require-with-a-variable-vs-using-a-string-in-webpack/37241982 – MEnf Mar 09 '22 at 15:23

1 Answers1

0

Resolved! Thanks @MEnf

Working code:

type FlagIconProps = {
    twoCharLocationCode: string
    widthPx?: string
}

const FlagIcon = ({ twoCharLocationCode, widthPx = '24px' }: FlagIconProps) => {

    const flagIconImg: string = require(`./${twoCharLocationCode}.svg`)

    return (
        <img
            src={flagIconImg}
            className="flag-icon"
            alt="flag-icon"
            width={widthPx}
        />
    )
}

export default FlagIcon

Force Hero
  • 2,674
  • 3
  • 19
  • 35