Home > Back-end >  I keep getting TypeScript Error 2322 in react
I keep getting TypeScript Error 2322 in react

Time:01-10

I keep getting ts error

(Type 'string | { englishResults: {}; "": any; }' is not assignable to type 'ReactNode'.
  Type '{ englishResults: {}; "": any; }' is not assignable to type 'ReactNode'.
    Object literal may only specify known properties, and 'englishResults' does not exist in type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactFragment | ReactPortal'.ts(2322))

while creating an array from data (object) I get from localStorage. I wanted to create an array from the object using Object.keys() function. But the returned array keeps triggering the above error. I have tried different methods to solve the issue but to no avail. I am stuck.

Here is the code

const Admin = () => {
  const { adminId } = useParams();
  const navigate = useNavigate();

  const [results, setResults] = useState(false);
  const [studentEnglishResults, setStudentEnglishResults] = useState({});
  const [englishResults, setEnglishResults] = useState({});

  if (localStorage.length > 0) {
    setResults(true);
    setStudentEnglishResults(JSON.parse(
      localStorage.getItem("englishAnswers")!
    ));
    setEnglishResults(Object.keys(studentEnglishResults));
  }

  const adminUser = adminUsers.find(
    (adminUser) => adminUser.adminId === adminId
  );

  useEffect(() => {
    if (adminUser?.adminId !== adminId) {
      navigate("/");
    }
  }, []);

  const clearResult = () => {
    localStorage.clear();
  };

  const backToLogin = () => {
    navigate("/");
  };

  return (
    <>
      <div className="bg-gray-400 mx-auto w-3/4 p-3 mt-5">
        <p className="capitalize font-serif">
          <span className="font-bold">Admin</span>
        </p>
      </div>

      <div className="shadow-md shadow-gray-500 w-2/4 mx-auto p-5">
        <table className="table-auto border-collapse border w-full">
          <thead>
            <tr>
              <th className="text-left">Question</th>
              <th className="text-left">Answer</th>
            </tr>
          </thead>
          <tbody>
            //the error comes from this line
            { results ? {englishResults.map((item, index) => {
              return (
                <tr key={index}>
                  <td className="">{item}</td>
                  <td>{(studentEnglishResults as any)[item]}</td>
                </tr>
              );
            })} : ''}
          </tbody>
        </table>
      </div>
    </>
  );
};

export default Admin;

CodePudding user response:

What is the type of values that studentEnglishResults[item] may have? React cannot magically figure out what to do if you give it a random object and TS is trying to prevent any runtime error that may arise from giving it a type that it doesn't know how to deal with.

If you are certain that it is one of the types that can be rendered, tell that to TypeScript by specifying its type. Otherwise, change the type to something that React can render (stringifying any object will at least make react be able to render it, as compared to throwing an error, but that's probably not what you want).

CodePudding user response:

This defines englishResults as an object:

const [englishResults, setEnglishResults] = useState({});

But you try to use it like an array by calling map on it. I see that you're trying to convert the object to an array with Object.keys, but you can't dynamically change the type of something In Typescript, you will get a lot of type errors if you do.

Also this is syntactically incorrect code:

results ? {englishResults.map(...)} : ""

You should not use braces here.

  • Related