Home > Net >  React Native: How to add new element at the top of the list using Hooks and render using map()?
React Native: How to add new element at the top of the list using Hooks and render using map()?

Time:06-30

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>
        ))}

CodePudding user response:

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.

  • Related