Search code examples
javascripthtmlreactjsundefinedgithub-api

TypeError: Cannot read property 'ft' of undefined API


So I'm doing some html javascript business in VS Code for a class in uni. We use React and some other stuff. My problem is with my API: https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/en.1.json So I'm trying to load the data from it.

My problem is that I'm trying to access the scores of the matches that have scores defined and it works at the index + 3 but the {data[index].score.ft[0]} - {data[index].score.ft[1]} part doesnt work because that specific match doesnt have score defined. I want to solve it somehow that my code doesnt try to load informartion from those not defined but instead it write something like " no information" or such.

Full code(I know its ugly, I'm a noob in web development):

import React, { useEffect, useState } from "react";
import axios from 'axios';

export default function Eredmeny() {

const [data, setData] = useState([]);
const [index, setIndex] = useState(0);



useEffect(() => {
    const load = async () => {
        const {data: { matches } } = await axios( 
            "https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/en.1.json" );
        setData(matches);
        //console.log(data);
    }
    load()
}, [])

const prev = () => {
    if( index >= 10){
    setIndex(index - 10);
    }
}

const next = () => {
    if( index <= data.length-11){
    setIndex(index + 10);
    }
}

if (data.length <= 0) {
    return "Loading..."
}

return(
    <div>
        <h1>
            <button onClick = {prev}>Previous</button>
            {data[index].round}
            <button onClick = {next} >Next</button>
        </h1>

        <h3>
            <p>{data[index].team1} - {data[index].team2}</p>
            {data[index].score.ft[0]} - {data[index].score.ft[1]}
            <p> {data[index+1].team1} - {data[index+1].team2}</p>
            <p> {data[index+2].team1} - {data[index+2].team2}</p>
            <p> {data[index+3].team1} - {data[index+3].team2}</p>
            {data[index+3].score.ft[0]} - {data[index+3].score.ft[1]}
            <p> {data[index+4].team1} - {data[index+4].team2}</p>
            <p> {data[index+5].team1} - {data[index+5].team2}</p>
            <p> {data[index+6].team1} - {data[index+6].team2}</p>
            <p> {data[index+7].team1} - {data[index+7].team2}</p>
            <p> {data[index+8].team1} - {data[index+8].team2}</p>
            <p> {data[index+9].team1} - {data[index+9].team2}</p>

        </h3>

        


    </div>
    
);

}

Solution

  • As some of your record doesn't have score object, give a null check before accessing the value like below.

    {data[index].score ? (data[index].score.ft[0] - data[index].score.ft[1]): ''}