Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

typescript - The property favorited does not exists at the object

I am calling the third-party API and the data does not have the favorited property, then I added the property favorited at the interface StocksProps:

Interface StocksProps

interface StocksProps {
  id: number;
  name: string;
  ticker: string;
  minimumValue: number;
  profitability: number;
  favorited: boolean;
}

But at the time when I call the API I use the setStocks remembering that this API call is inside the useEffect hook. The API data comes

"success":true,
"data":[
 {
   ...
 },
 {
   ...
 },
],
"error": null

API get

api.get('stocks').then((response) => {
  const stocksDataOrdered =
    response.data.data.sort((stockA: StocksProps, stockB: StocksProps) =>
      stockA.name.localeCompare(stockB.name));
  setStocks(stocksDataOrdered);
  setLoading(false);
});

And I'm trying to make the heart empty, full after I click on the heart, but when I give a console.log () in the action that has the id, it doesn't come with any properties called favorited.

const handleStockAsFavorite = useCallback((id: number) => {
   const stockToChangeTheFavoriteValue = stocks.find(element => element.id === id);
   console.log(stockToChangeTheFavoriteValue);
   setFavoriteStock(false)
}, [stocks]);
<FavoriteButton onPress={() => handleStockAsFavorite(stock.id)}>
    <FavoriteImage source={favoriteStock ? favoritedImg : unfavoriteImg} />
</FavoriteButton>

The log comes {"id": 3, "minimumValue": 400.2, "name": "Banco do Brasil Seguridade", "profitability": 27.05, "ticker": "BBSE3"}

question from:https://stackoverflow.com/questions/65878702/the-property-favorited-does-not-exists-at-the-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you create an interface in typescript, you're really just making a note that you intend to use it that way. The interface is actually completely removed from the compiled javascript, it's only used to make sure you don't accidentally access properties that you said don't exist. If you want to add a new property that the API doesn't give you, you'll need to explicitly set it on each object as it comes in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...