Home > Blockchain >  Uncaught TypeError: Cannot read properties of null (reading 'original')
Uncaught TypeError: Cannot read properties of null (reading 'original')

Time:05-03

When creating a simple training project, an error flies into me.

Uncaught TypeError: Cannot read properties of null (reading 'original')
    at Character (Character.js:7:1)
    at renderWithHooks (react-dom.development.js:16175:1)
    at mountIndeterminateComponent (react-dom.development.js:20913:1)
    at beginWork (react-dom.development.js:22416:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
    at invokeGuardedCallback (react-dom.development.js:4274:1)
    at beginWork$1 (react-dom.development.js:27405:1)
    at performUnitOfWork (react-dom.development.js:26513:1)
    at workLoopSync (react-dom.development.js:26422:1)

Moreover, if you quickly refresh the page, you can see the images with which the error occurs, and links to the images are working.

Fake API when I took date

https://api.tvmaze.com/characters/1

App.js

import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import Character from "./components/Character";

function App() {
  const [characters, setCharacters] = useState([]);

  useEffect(() => {
    for (let i = 1; i <= 100; i  ) {
      characterFetch(i);
    }
  }, []);

  async function characterFetch(id) {
    fetch("https://api.tvmaze.com/characters/"   id)
      .then((response) => response.json())
      .then((json) =>
        setCharacters((lastcharacters) => [...lastcharacters, json])
      );
  }

  return (
    <div className="App">
      {characters.map((character) => {
        return <Character character={character} key={character.id} />;
      })}
    </div>
  );
}

export default App;

Character.js

import React from "react";

const Character = (props) => {
  if (props.character.name !== "Not Found") {
    var construct = (
      <>
        <img src={props.character.image.original} alt="Character_photo" />  //error
        <div> {props.character.id} </div>
        <div>{props.character.name}</div>
      </>
    );
  }
  return <div>{construct}</div>;
};

export default Character;

CodePudding user response:

For some of the characters, the image is null.

Example: https://api.tvmaze.com/characters/15

That's why you are getting as

Cannot read properties of null

To fix it, you can use Optional Chaining or check with a simple if else

Example:

props.character.image?.original
  • Related