Reputation: 229
I have one component, that should get from api and render data with diferent variable names. I have two response with same data but with diferent variable names for example:
FirstReq {
id number
published boolean
publishDate string
newsImage string
newsText string
newsTitle string
}
SecondReq {
anons string
archived boolean
fullText string
id number
postingDate string
title string
}
Usualy i used it by variable names:
interface ItemProps {
item: {
id: number,
title: string,
fullText: string,
anons: string,
postingDate?: string,
image?: string,
},
}
const Item: React.FC<ItemProps> = (props) => {
const { item } = props;
const { id, postingDate, title, anons, image, fullText } = item;
return (
<>
<div>{title}</div>
<div>{postingDate}</div>
<div>{fullText}</div>
</>
)
}
export default Item
But how can I write component to use it with diferent variable names? variable for "text" can be "fullText" or "newsText" or "articleText" is it possible to render it in one universal component? Have no idea how to write it. Can anyone help, or give advice how to do it?
Upvotes: 2
Views: 82
Reputation: 1542
IMO the best solution is always to unify received data from different APIs, if this is not possible for any reason and should be handled from your side, there're different ways to handle this, my recommendation as an efficient way is to have a unique interface, and map your data to create a model that matches that interface
ex:
interface ItemInterface {
id: number,
title: string,
postingDate?: string,
...
}
and you get different responses, one with postingDate
and the other with a different name publishDate
, so you can do something like:
class Item implements ItemInterface {
constructor(itemData) {}
get postingDate() {
return itemData.postingDate || itemData.publishDate;
}
...
...
}
then in your component, you can do:
const { id, postingDate, title, anons, image, fullText } = new Item(item);
actually, you can achieve the same by creating a new simple object that gets the values in a similar way:
const unifiedItem: ItemInterface = {
postingDate: itemData.postingDate || itemData.publishDate
...
}
Some more recommendations:
interface ItemPropsInterface {
item: ItemInterface
}
const Item: React.FC<ItemProps> = ({item}) => {
Upvotes: 1