简体   繁体   中英

React TypeScript iterating over array full of objects using Array.prototype.map

Currently, I am working on my first TypeScript project using React. However, I don't know TypeScript and planned to focus on its static types later at some point, meanwhile preparing the whole structure in regular JS. This React app connects with my personal API and fetches data from there. In regular JS I would normally fetch data in useEffect hook and add the fetched data using spread operator like that setSomeData([...response.data]) , but it warned me Type any[] is not assignable to never[] so I had to do this instead setSomeData(response.data); .

Second major problem is that when I want to populate this data from array inside of the component I am not able to compile the project since I get following error property make doesn't exist on type never

React Component:


import { useEffect } from "react";

import carsService from "../services/cars.service";

function Main() {

  const [vehiclesList, setVehiclesList] = useState([]);


  useEffect(() => {
    carsService
      .getCars()
      .then((response) => {
        console.log(response.data);
        return setVehiclesList(response.data);
      })
      .catch((err) => console.error(err));
  }, []);

  return (
    <div className="main-container">
      <div className="makes-list">
        {vehiclesList.map((vehicle, index) => {
          return (
            <div key={index}>
              <p>{vehicle.make}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object Model:

const carSchema = new Schema(
  {
    carId: { type: String, unique: true, require: true },
    make: { type: String, unique: true, require: true },
    models: [
      {
        name: { type: String, unique: true },
        reviews: [
          {
            Version: { type: String, require: true },
            Year: { type: Number, require: true },
            Engine: { type: String, requite: true },
            General: { type: String, require: true },
            Pros: { type: String, require: true },
            Cons: { type: String, require: true },
            User: { type: String, require: true },
            Date: { type: Date, default: Date.now },
          },
        ],
      },
    ],
  },
  {
    timestamps: {
      createdAt: "createdAt",
      updatedAt: "updatedAt",
    },
  }
);

Declare the TypeScript interfaces for the vehiclesList .

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

import carsService from '../services/cars.service';

interface Review {
  Version: string;
  Year: number;
  Engine: string;
  General: string;
  Pros: string;
  Cons: string;
  User: string;
  Date: Date;
}

interface Model {
  name: string;
  reviews: Review[];
}

interface Car {
  carId: string;
  make: string;
  models: Model[];
  createdAt: string;
  updatedAt: string;
}

function Main() {
  const [vehiclesList, setVehiclesList] = useState<Car[]>([]);

  useEffect(() => {
    carsService
      .getCars()
      .then((response) => {
        console.log(response.data);
        return setVehiclesList(response.data);
      })
      .catch((err) => console.error(err));
  }, []);

  return (
    <div className="main-container">
      <div className="makes-list">
        {vehiclesList.map((vehicle, index) => {
          return (
            <div key={index}>
              <p>{vehicle.make}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM