Search code examples
javascriptreactjstypescriptreact-hooksreact-tsx

How can i add "ids" to data fetched from an outside api?


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


Solution

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