Home > Software engineering >  Not able to pass Array into another component in react
Not able to pass Array into another component in react

Time:11-26

response is an array returned by my API. I am passing this variable to another component to create table in UI.

const [response, setResponse]= useState([]);
  useEffect(() => {
    (
      async () => {
        await axios.get('http://localhost:3000/api/certificates').
        then(response=>{
            setResponse(response.data);
            setFlag(true);
        })   
     }
    )()
  }, []);

I am using this response to another component to create table.

const ResultTable = (response: any[]) => {
-----------code------
----------code------
}

I am calling component like below.

                    <tbody> 
                      <ResultTable response={response}/>  //this line giving error
                    </tbody>

enter image description here

what mistake I am doing?

if I do like below

({response}: any[]) 

it does not recognize response variable. my file is .tsx enter image description here

CodePudding user response:

Your ResultTable component should looks something like this,

const ResultTable = ({ response }) => {
-----------code------
----------code------
}

CodePudding user response:

Try updating the destructuring at ResultTable as:

const ResultTable = ({response}: any[]) => {
-----------code------
----------code------
}

Also, update the state initialization as

const [response, setResponse]= useState<any[]>([]);

CodePudding user response:

I just learned this too but empty array is automatically infered to the type "never". I believe if you change your useState hook to this:

 useState([] as any);

it will work.

And also change this one to const ResultTable = ({ response })

  • Related