0

I have some JSON that is formatted like this:

{
    card_id: "afe1500653ec682b3ce7e0b9f39bed89",
    name: "A.J. Burnett",
    playerattribute: {
        team: "Marlins",
        rarity: "Diamond",
    }
}

I'm attempting to display the name and the team in a component. Here is what I have.

const PlayerProfile = ({ match, location }) => { 
    const { params: { cardId } } = match;
    const [player, setPlayer] = useState(0);
 
    useEffect(() => {
        const fetchData = async () => {
          const result = await axios(
            `http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
          ).then((result) => {
            setPlayer(result.data);
          });
        };
        fetchData();
      }, []);

    return (
        <Container component="main">
            Name: {player.name}
            Team: {player.playerattribute.team}
        </Container>
    )
}

export default PlayerProfile;

However, I get this error: TypeError: Cannot read property 'team' of undefined

The name works fine. So I'm assuming it's an issue with the nested JSON.

JeremyE
  • 1,368
  • 4
  • 20
  • 40
  • Because at first render when data not came, player's value is 0. Add condition like if player.name then show name and team – Zuhair Naqi Mar 17 '21 at 08:12
  • 1
    Here is the problem: `const [player, setPlayer] = useState(0);`, `player.playerattribute` => `((0).playerattribute)` => `undefined`. And, `{player.playerattribute.team}` => `undefined.team` – Ajeet Shah Mar 17 '21 at 08:15
  • Does this answer your question? [How to avoid 'cannot read property of undefined' errors?](https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors) – Ajeet Shah Mar 17 '21 at 08:23

3 Answers3

1

You probably shouldn't instanciate your player state with 0 if the projected value is an object.

The error comes up because you try to access a property of an object property that doesn't exist at creation.

Basically, your code tries to do this: {0.playerattribute.team}

0.playerattribute => undefined

Workaround would be a conditionnal render or a default initial value of your state that matches the JSX needs.

const PlayerProfile = ({ match, location }) => { 
const { params: { cardId } } = match;
const [player, setPlayer] = useState({
    name: "",
    playerattribute: {
        team: ""
    }
});

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
      ).then((result) => {
        setPlayer(result.data);
      });
    };
    fetchData();
  }, []);

return (
    <Container component="main">
        Name: {player.name}
        Team: {player.playerattribute.team}
    </Container>
)
}

export default PlayerProfile;

or

const PlayerProfile = ({ match, location }) => { 
const { params: { cardId } } = match;
const [player, setPlayer] = useState(null);

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
      ).then((result) => {
        setPlayer(result.data);
      });
    };
    fetchData();
  }, []);

return (
    <Container component="main">
        Name: {player?.name}
        Team: {player?.playerattribute?.team}
    </Container>
)
}

export default PlayerProfile;
Pierre Burton
  • 1,954
  • 2
  • 13
  • 27
0

Set useState const [player, setPlayer] = useState("");

0
const [player, setPlayer] = useState({
Name: '',
Team: ''
}}

//on your setPlayer you may 
const playerData = result.data;
setPlayer({
Name: playerData.name
Team: playerData.playerattribute.team})

if you still getting same error, please provide screenshot of console.log(result)

Rymrk
  • 216
  • 1
  • 3
  • 13