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.

3
  • Because at first render when data not came, player's value is 0. Add condition like if player.name then show name and team Commented Mar 17, 2021 at 8:12
  • 1
    Here is the problem: const [player, setPlayer] = useState(0);, player.playerattribute => ((0).playerattribute) => undefined. And, {player.playerattribute.team} => undefined.team Commented Mar 17, 2021 at 8:15
  • Does this answer your question? How to avoid 'cannot read property of undefined' errors? Commented Mar 17, 2021 at 8:23

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.