Home > Software design >  Extract the array out of an object in React
Extract the array out of an object in React

Time:10-08

For my React app, I have a function Query2 in a file service.ts such as:

interface Result {
   products: number[];
}

export async function Query2(molsSdf: string): Promise<Result>

{ 
   return  {products: [0.1]}    
}

In my component "draw1.jsx" file where I am importing my function Query2, I have these lines of codes:

import React, { useEffect, useState } from 'react';
import {Query2} from '../common-services/service.ts'

const [products, setProductivities] = useState([]);

    async function handleSearch () {

        const mol = window.JSDraw.get("test").getMolfile()

        const pds = await Query2(mol)

        setProductivities(pds)
    }
return ( 
            <div className="button">

                <Button onClick={handleSearch}>Search</Button>      

            </div> 

            <h1>

            {products.map(tox =>

                    <li>
                        Toxs
                    </li>
                )
            }

            </h1>

    );
}

export default Draw1;

   

" const pds = await Query2(mol) " is not getting an array back. I am passing "pds" to "setProductivities as if it's an array, but it's not an array, it's an object. How can I extract the array out of the object "pds" and pass that to setProductivities?

CodePudding user response:

Because your function returns object with products property which is an arry. You need change to this:

  setProductivities(pds.products)

CodePudding user response:

You can destructure the products key out of the object which is an array.

const { products } = await Query2(mol)
setProductivities(products)

You can also alias the destructured key to pds (if required).

const { products: pds } = await Query2(mol)
setProductivities(pds)

Or you can simply access the products key from the object, following is one way of doing the same.

const pds = (await Query2(mol)).products
setProductivities(pds)
  • Related