Дополнительная цепочка для вызова JSON API не работает в React - PullRequest
0 голосов
/ 29 мая 2020

Итак, я делаю вызов GET в React, используя библиотеку fetch. Это схема:

{
  "originatingRequest": {
    "clientId": 1,
    "simulationName": "Season 2020",
    "teamRatings": [{
        "teamId": 1,
        "rating": 2.5
      },
      {
        "teamId": 2,
        "rating": 0.85
      },
      {
        "teamId": 3,
        "rating": 1.35
      },
      {
        "teamId": 4,
        "rating": 1.35
      }
    ],
    "simulationId": "7d49cb14-d99e-4315-bba3-077d114ab6fc"
  },
  "markets": [{
      "name": "Winner",
      "selections": [{
          "name": "Manchester City",
          "probability": "0.25"
        },
        {
          "name": "Manchester United",
          "probability": "0.25"
        },
        {
          "name": "Liverpool",
          "probability": "0.25"
        },
        {
          "name": "Chelsea",
          "probability": "0.25"
        }
      ]
    },
    {
      "name": "Top Two",
      "selections": [{
          "name": "Manchester City",
          "probability": "0.95"
        },
        {
          "name": "Manchester United",
          "probability": "0.05"
        },
        {
          "name": "Liverpool",
          "probability": "0.95"
        },
        {
          "name": "Chelsea",
          "probability": "0.05"
        }
      ]
    }
  ],
  "created": "2020-05-27T11:12:43.467644"
}

Меня интересует массив markets, и я хочу, чтобы вероятности были возвращены для рынка Winner в таблице. Этот компонент визуализируется с помощью перенаправления, следовательно, useLocation() для получения идентификатора параметра.

На днях меня направили на необязательную цепочку, поэтому я провожу некоторую проверку, чтобы увидеть, есть ли какие-либо значения в объекте, если не вернуть null. Несмотря на то, что console.log() возвращает объект, кажется, что окончательная таблица имеет вид null:

function SimulationReport(props) {

  const location = useLocation();

  const [simResult, setSimResult] = useState(
    getSimById(location.state.simId)
  );


  return (
    <GridWrapper>
      <div>
        <TableWrapper>
          <Table striped bordered hover size="sm" responsive>
            <thead>
              <tr className="same-col-widths">
                <th>Team Name</th>
                <th>Win Probability</th>
              </tr>
            </thead>
            <tbody>
              {simResult?.markets?.length
                ? simResult.markets
                    .find(t => t.name === "Winner")
                    .selections.map(selection => (
                      <tr key="">
                        <td>{selection.name}</td>
                        <td>{selection.probability}</td>
                      </tr>
                    ))
                : null}
            </tbody>
          </Table>
        </TableWrapper>
      </div>
    </GridWrapper>
  );
}

export default SimulationReport;

Это вызов API, который был открыт:

export function getSimById(simId) {
  return fetch(simsUrl + "/results/" + simId, {
    method: "GET"
  })
    .then(handleResponse)
    .catch(handleError);
}

И обработка ответа:

export async function handleResponse(response) {
  if (response.ok) {
    let someResponse = response.json();
    console.log("loading response");
    console.log(someResponse);
    return someResponse;
  }

  if (response.status === 400) {
    // So, a server-side validation error occurred.
    // Server side validation returns a string error message, so parse as text instead of json.
    throw new Error(error);
  }

  const error = await response.text();
  console.log("error was: " + error);
  console.log("status was: " + response.status);
  throw new Error("Network response was not ok.");
}

// In a real app, would likely call an error logging service.
export function handleError(error) {
  // eslint-disable-next-line no-console
  console.error("API call failed. " + error);
  throw error;
}

Как мне заполнить окончательный отрендеренный Table рыночными вероятностями Winner?

...