Search code examples
reactjstypescriptflowtype

Cannot assign to 'current' because it is a read-only property


I am trying to have a useRef obj to be either null or a function here is code snippet

import "./styles.css";
import { useState, useRef, useEffect } from "react";
export default function App() {
  const testRef = useRef<string | null>(null);
  const unblockRef = useRef<() => void | null>(null);

  useEffect(() => {
    const test = () => {
      console.log("hey");
    };

    testRef.current = "";

    // this would give the error code
    unblockRef.current = null;
    // unblockRef.current = "saddsa";
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

here is playground link, from other stack overflow post, it seems like i just need to pass null type when we initialize the useRef obj.

I test the logic with testRef, which works fine, it seems like if the useRef type is function that would give trouble, Thanks for any kinds of help!


Solution

  • It's simply a TypeScript error. Your syntax is problematic:

    const unblockRef = useRef<() => void | null>(null);
    

    This is interpreted as a function that returns either void or null.

    So, you need to make sure it's a function or null:

    const unblockRef = useRef<(() => void) | null>(null);