How to add new object at specific position of useState Hooks array

Asked

Viewed 43 times

0

I have the following state in hook on Reactjs:

const[faixas, setFaixas] = useState([
          {albumId: 1, nome: "nome da musica"}, 
          {albumId: 1, nome: "nome da musica"},
          {albumId: 2, nome: "nome da musica"}
])
const[albuns, setAlbuns] = useState([
         {id: 1, nome: "nome do album"}, 
         {id: 2, nome: "nome do album"}
])

So what I’m trying to do is, I have an array of tracks that will tell me what album she’s on by albumId. I therefore need that in the state album i have an array of tracks, so the albuns state would look like this :

albuns([{id: 1, nome: "nome do album", 
               faixas: {
                {albumId: 1, nome: "nome da musica"}, 
                {albumId: 1, nome: "nome da musica"}
                       }, 
         {id: 2, nome: "nome do album", 
               faixas: {
                {albumId: 2, nome: "nome da musica"}
                       }]
           ) 

how can I do this? I couldn’t do it using useState changes:

setAlbuns((prev:any) => {
        return [...albuns, faixas.albumId]
      })

I don’t know how I could do that,

1 answer

2


Using map to interact on each item of your array and the filtro that will bring the filtered data of the other array can assemble the structure as shown in the question, example:

function App() {
  const[faixas, setFaixas] = React.useState([
          {albumId: 1, nome: "nome da musica"}, 
          {albumId: 1, nome: "nome da musica"},
          {albumId: 2, nome: "nome da musica"}
  ]);
  const[albuns, setAlbuns] = React.useState([
         {id: 1, nome: "nome do album"}, 
         {id: 2, nome: "nome do album"}
  ]);
  function merge() {
    const result = albuns.map((a) => {
      a.faixas = faixas.filter(x => x.albumId === a.id);
      return a;
    });
    setAlbuns(result);
  }
  React.useEffect(() => {
    merge();
  },[]);
  return (
    <pre>{JSON.stringify(albuns, null, 1)}</pre>
  )
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.