简体   繁体   中英

append/add/unshift an object to the beginning of an response from an api

When the data is returned from an api call i would like to add extra data to the data returned from the api call. So far i have got the data from the backend but i want to append extra data to the beginning of the data returned from the backend. I am unsure how to do this.

export const getMessageTemplates = (): Promise<
  ReadonlyArray<MessageTemplate>
> =>
  fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
    method: "get",
    credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
    headers: {
      Accept: "application/json",
    },
  }).then(res=>res.json())
  .then(data=>data.unshift(
    {templateId: " ", category: "", title: "blank message", defaultTemplate:false}
    )).then(data=> data);
    

data.unshift returns the length of the updated data array. Just change that implementation like so to return data explicitly:-

export const getMessageTemplates = (): Promise<
  ReadonlyArray<MessageTemplate>
> =>
  fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
    method: "get",
    credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
    headers: {
      Accept: "application/json",
    },
  })
  .then(res=>res.json())
  .then(data=>
    {data.unshift(
    {templateId: " ", category: "", title: "blank message", defaultTemplate:false})
    return data;
    }).then((data)=>// do whatever with data);

Although you can prevent using that additional then chaining and the callback for data in the end and just use it in the previous one where you use unshift .

Try this approach:

fetch('https://reqres.in/api/users')
    .then(res => res.json())
    .then(res => {
        res.data.unshift({templateId: " ", category: "", title: "blank message", defaultTemplate:false});
        console.log(res.data) // new updated array
    });

Lakshya's solution works perfectly for what you need and is a great answer.

If you'd like to get the same result you're looking for without using unshift() , you can also use the spread operator to return the new array to data inline without a return statement:

export const getMessageTemplates = (): Promise<
  ReadonlyArray<MessageTemplate>
> =>
  fetch(REACT_APP_BACKEND_LOCATION + "/api/template", {
      method: "get",
      credentials: REACT_APP_BACKEND_LOCATION === "." ? "same-origin" : "include",
      headers: {
        Accept: "application/json",
      },
    })
    .then(res => res.json())
    .then(data => [{ templateId: " ", category: "", title: "blank message", defaultTemplate: false }, ...data])
    .then((data) => /* your logic here */);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM