Place one state array inside another

Asked

Viewed 30 times

-1

I wonder how I can put the contents of an array that is with true status within another array, for example: { id:1, Fruit:'Banana', status:true }, { id:2, Fruit:'Orange', status:true }, { id:3, Fruit:'Lemon', status:true }

I tried to do according to the code below, but it is putting the item as an array inside the other and not only the content:

inserir a descrição da imagem aqui

const [fruits,setFruits] = useState([
    {
        id:1,
        fruit:'Banana',
        status:true,
    },
    {
        id:2,
        fruit:'Orange',
        status:true
    }
]);
const [newFruit, setNewFruit] = useState([
    {
        id:3,
        fruit:'lemon',
        status:true
    },
    {
        id:4,
        fruit:'morango',
        status:false
    }
]);

JSX code below:

return (
    <div>
        {fruits.map((fruits,index)=>
            <span key={index}>{fruits.fruit}, </span>
        )
        }
        <button onClick={Add}>Adicionar</button>
    </div>
);

Function to add new fruit:

const Add = () =>{
    const filtered = newFruit.map((fruit)=>
        fruit.status === true 
        ?   {
                fruit
            }

        :   {
                
            }
    )
    
    setFruits([
        ...fruits,
        filtered
    ])
    console.log(fruits)
}

1 answer

3

Just dismantle the array filtered as you did with the array fruits:

setFruits([
    ...fruits,
    ...filtered
]);

But it also has the detail that this array filtered is not being mounted correctly. You are generating it with the method map, that generates a new array the same size as array in which it was called, and in your code you are returning an empty object when it does not pass by your condition fruit.status === true. This is unnecessary, you can only use the method filter to generate a new array:

const filtered = newFruit.filter((fruit) => fruit.status);

setFruits([
    ...fruits,
    ...filtered
]);
    
  • Opa, really got as I expected, did not know that I could destroy the tb Filtered. Thank you very much!

Browser other questions tagged

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