简体   繁体   中英

How to create reusable method to handle API returning single object getByID and array of objects by getAll in React.js

I have react application where data is fetched byId or getAll. Currently I have return component which map over array of object and display details, I want to use same component to display details when data is fetched from getById which returns single object(Not Array of Objects). But my code is failing stating map is not defined since map is only available for array object.

How can I solve this and same component can be used for display result.

Single Object:

{id: 1, paymentDate: "Wed Nov 11 08:13:43 UTC 2020", type: "CREDIT CARD", custid: 12345}

Array of objects: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

payments.map((payment) => {
                        return (
                            <div key={payment.id} style={{ width: "50%" }}>
                                {/* <PaymentTitle custid={payment.custid} /> */}
                                <PaymentDetails payment={payment} />
                            </div>
                        );
                  })

You can write a condition that check whether the response is an array, if it is you can use the spread operator, otherwise you add the single element to an empty array.

let payments = Array.isArray(res) ? [...res] : [res];
payments.map((payment) => console.log(payment));

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