Home > Software engineering >  How can i add "ids" to data fetched from an outside api?
How can i add "ids" to data fetched from an outside api?

Time:07-23

Good evening everyone,

I have the following code for fetching the data from an api i prepared:

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(BOOKS_API);
      setBookData(result.data);
    };
    fetchData();
  }, []);

This is how the data looks (raw api call) ->

{
    "bookName": "Thus Spoke Zarathustra",
    "bookGenre": "Philosophical",
    "pageCount": 327,
    "bookAuthorName": "Friedrich Nietzsche",
    "isbnNumber": "9780521602617"
  },
  {
    "bookName": "Beyond good and evil",
    "bookGenre": "Philosophical",
    "pageCount": 301,
    "bookAuthorName": "Friedrich Nietzsche",
    "isbnNumber": "9780394703374"
  },

My website functionalities require an additional "id" property, a 'final' object would look like this:

{
    id: 1,
    bookName: 'Thus Spoke Zarathustra',
    bookGenre: 'Philosophical',
    pageCount: 327,
    bookAuthorName: 'Friedrich Nietzsche',
    isbnNumber: '9780521602617',
  },

My question is - How can i append this data fetched from my api with an "id" field, which will always be enumerated from 1 - n? (n-number of rows fetched)

Thank you in advance

CodePudding user response:

Just call .map on the response and set the id field to the index 1:

let bookData = [];

const setBookData = (data) => {
    bookData = data;
}

const apiResponse = [
{
    "bookName": "Thus Spoke Zarathustra",
    "bookGenre": "Philosophical",
    "pageCount": 327,
    "bookAuthorName": "Friedrich Nietzsche",
    "isbnNumber": "9780521602617"
  },
  {
    "bookName": "Beyond good and evil",
    "bookGenre": "Philosophical",
    "pageCount": 301,
    "bookAuthorName": "Friedrich Nietzsche",
    "isbnNumber": "9780394703374"
  }
];

setBookData(apiResponse.map((el, index) => {
    return { ...el, "id": index 1 }
}));

console.log(bookData);

CodePudding user response:

useEffect(() => {
    const fetchData = async () => {
        const { data } = await axios(BOOKS_API);
        const formattedResult = data.map((res, index) => {
            return { ...res, id: index   1 }
        });
      
        setBookData(formattedResult);
    };

    fetchData();
}, []);
  • Related