Julián Oviedo
Julián Oviedo

Reputation: 730

A hook as an array

There is this interface:

export interface msgX{
    user:any
    msg:any
    day:any
    time:any
  }

Then I define a hook array like this:

const [arrayMsg, setArrayMsg] =  useState <msgX> ( )

Because I get data from an API:

axios.get(url+"chat/"+props.ticket).then((resp: { data: any; }) => {
 for (let i=0; i<resp.data.length;i++){
     arrayMsg.push({user:resp.data[i].user,msg:resp.data[i].msg, day:resp.data[i].day, time:resp.data[i].time})
 }

})

But I can not make a push to that array hook.

I can not define a hook like this:

const [arrayMsg, setArrayMsg] =  useState <msgX> ([])

To do this:

axios.get(url+"chat/"+props.ticket).then((resp: { data: any; }) => {
 for (let i=0; i<resp.data.length;i++){
     array.push({user:resp.data[i].user,msg:resp.data[i].msg, day:resp.data[i].day, time:resp.data[i].time})
 }
setArrayMsg(array)
})

What can I do?

Upvotes: 0

Views: 56

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

first you need to change your state to this:

const [arrayMsg, setArrayMsg] = useState<msgX[]>([]);

and then change this:

axios.get(url + "chat/" + props.ticket).then((resp: { data: any }) => {
  setArrayMsg(
    resp.data.map((d) => ({
      user: d.user,
      msg: d.msg,
      day: d.day,
      time: d.time
    }))
  );
});

Upvotes: 1

Related Questions