Lex2000
Lex2000

Reputation: 229

How to use data with diferent variables names?

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

Answers (1)

Zac
Zac

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:

  • Have a separate interface for the item itself, then if you want to have props interface it can be, ex:
interface ItemPropsInterface {
  item: ItemInterface
}
  • also, some renaming can be useful to differentiate between things ( many things called item...)
  • if you want to get item from props you can have const Item: React.FC<ItemProps> = ({item}) => {

Upvotes: 1

Related Questions