0

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

  setProductivities(pds.products)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.