Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
React Native: How to add new element at the top of the list using Hooks and render using map()?

Im trying to add a new data and put it at the top of the array that I got from an API. The problem is that the new data is still at the end of the array and it only renders the new data instead of all of it even though the console.log output all of the data. I know the problem is not the style because it was able to render properly if I didn't add a new data.

This is how I add the new data:

    fetch()
    **********
    .then((result) => {
    setListTab(result);
    setListTab(listTab => [listTab, {id: 18, name: "All", ...listTab}]);
    console.log(listTab);


    <ScrollView 
        showsHorizontalScrollIndicator={false} 
        horizontal={true}>
        {listTab.map(item => (
            <TouchableOpacity key={item.id} 
                activeOpacity={1}> 
                <Text>{item.name}</Text>
            </TouchableOpacity>
        ))}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, off you should not use ScrollView to implement Lists, please use FlatList.

Your logic (as per the code you posted) is not right. To add a new object to the first of the array you can very well use the spread operator.

Example code: https://jsfiddle.net/rzhybtdj/

let friendsList = [{"id":343,"name":"Satheesh"}, {"id":342,"name":"Kavitha"}];
// something happened and I have a new friend now.
// To add it to the firendsList array I do this
const newFriend = {"id":341,"name":"Yuvan"};
friendsList = [newFriend, ...friendsList];

Now come to your code and how it should be to make what you want.

fetch()
.then((result) => {
const newList = [...result, ...listTab]; //considering result being an array, if an object then [result, ...listTab]
setListTab(newList);
console.log(newList);

Let me know if this works for you.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda