DEV Community

Discussion on: How To Export Data To Excel From Api Using React

Collapse
 
duysau profile image
duysau

Hi, I'm very intersting with your solution but how can I export columns that I want to export them. Example: I have id, displayID, name, age which of them are columns and I just want to export data from name, age.
Thanks for your supporting.

Collapse
 
jasurkurbanov profile image
Jasur Kurbanov • Edited

You need to change place where I am retrieving data from server. Add this code and analyze what I did. I put comments.

 React.useEffect(() => {
    const fetchData = () => {
      axios
        .get("https://jsonplaceholder.typicode.com/posts")
        .then((response) => {
          let newArray = [];

          response.data.map((item) => {
            // here i am  extracting only userId and title
            let obj = { userId: item.userId, title: item.title };
            // after extracting what I need, I am adding it to newArray
            newArray.push(obj);
            // now  I am adding newArray to localstate in order to passing it via props for exporting
            setData(newArray);
          });
        });
    };
    fetchData();
  }, []);
Enter fullscreen mode Exit fullscreen mode

Screenshot after exporing data. Checkout
dev-to-uploads.s3.amazonaws.com/up...

P.s
Regarding code style, I did simple solution in order to give you idea. Obviously, you can do code more beautiful and shorter.