Home > front end >  Render component after useEffect modification React JS
Render component after useEffect modification React JS

Time:03-04

I'm creating an app for TV and I need to create a QR Code with a value of a random code either fetched from localStorage or created on-the-fly if localStorage is null. The problem I'm facing is that the QR component is not being created on the first render (because "accessCode" is null), but after useEffect fills "accessCode", it still isn't being generated. The code:

const Login = () => {
  const [isLoading, setLoading] = useState(null);
  const [accessCode, setAccessCode] = useState(localStorage.getItem("access_code"));
  const [qrCode, setQRCode] = useState(null)
  useEffect(() => {
    let retrievedCode = localStorage.getItem("access_code");
    if (!retrievedCode) {
      retrievedCode = randomString(6, { special: false }).toUpperCase();
    }
    setAccessCode(retrievedCode);
    localStorage.setItem("access_code", retrievedCode);
  }, []);
return (
    <div className={styles.appMobileLogin}>
        {accessCode !== null ?? (
            <QRCode
            className={styles.qrContainer}
            value={accessCode}
            renderAs="svg"
            size={300}
            level="H"
        />)})
    </div>
}

I can't figure out how to re-render the component after the accessCode value has been updated.

CodePudding user response:

The Nullish Coalescing Operator (??) is preventing the QRCode component to be rendered because the expression is not null/undefined when acessCode exists.

Change with && instead.

{accessCode !== null && (
            <QRCode
            className={styles.qrContainer}
            value={accessCode}
            renderAs="svg"
            size={300}
            level="H"
/>)})

Explanation:

?? operator will return "its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand".

In your case, when accessCode is different than null, the expression accessCode !== null is false, so ?? will return the left-hand side operand (false), so nothing will be displayed.

CodePudding user response:

Seems like working for me,

Please refer the below code sandbox

https://codesandbox.io/s/affectionate-minsky-qr3n0f?file=/src/App.js

You may need to check how you are using the nullish operator change your operator to this

 {accessCode !== null ? (
            <QRCode
            className={styles.qrContainer}
            value={accessCode}
            renderAs="svg"
            size={300}
            level="H"
        />) : null})

or

 {accessCode !== null && (
            <QRCode
            className={styles.qrContainer}
            value={accessCode}
            renderAs="svg"
            size={300}
            level="H"
        />)})

for more on nullish coalescing operator refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

  • Related