React Native: Inserting new object inside Array

戏子无情 提交于 2021-02-15 07:13:38

问题


after successfully implementing sockets, i can now listen to my event from one screen to another. My problem now is that i want to display the new object that i obtained inside my flatlist.

Here is the new msg object:

messages: Object { "conversationId": 33, "message": "Heyy", "receiverId": 43, "senderId": 53, }

Here is my code:

const [listings, setListings] = useState([]);

const loadListings = async () => {
setLoading(true);
const response = await messagesApi.getMessages();
setLoading(false);
if(refreshing) setRefreshing(false);
if (!response.ok) return setError(true);
setError(false);
setListings(response.data)
};

useEffect(() => {
const newsocket = sockets(user.id);
setSocket(newsocket);
newsocket.on("send_message", (msg) => {
  console.log("messages:", msg);
  setListings(listings => [...listings,msg]);
});
loadListings()
}, []);

return (
<FlatList
    data={listings}
    keyExtractor={(listing) => listing.id.toString()}
    renderItem={({ item,index }) => (
      <MessagesList
      title={item.Listing.title}
        subTitle={item.Messages[0].message}
        imageUrl={item.images[0].url}
        thumbnailUrl={item.images[0].thumbnailUrl}
        // onPress={() => console.log("message selected", item)}
        onPress={() => navigation.navigate(routes.CHAT, 
                 {message:item,index,updateView,newsocket:socket})}
      />
    )}
  />
)

When i run this code i keep getting TypeError: undefined is not an object evaluating listing.id.toString.

I think i am getting this error since this new message object wants to get rendered live without getting it for database and hence it is still not given an id.

How do i go ahead and fix this?

Additional info

console.log(listings[0]) prints this

Object{ 
        "id":33,
       "Listing":{    
                  "title": "test",
                 },
       "Messages":Array[
                  Object {
                          "conversationId": 33,
                          "id": 601,
                          "message": "Hey",
                          },
                   Object {
                          "conversationId": 33,
                          "id": 600,
                          "message": "Hey",
                          },
                        ],
        "images":Array[
                 Object {"url":"","thumbnailUrl":""}]
      }

console.log(listings.map(x=>x.Messages))

 Array[
       Array[
                  Object {
                          "conversationId": 33,
                          "id": 601,
                          "message": "Hey",
                          },
                   Object {
                          "conversationId": 33,
                          "id": 600,
                          "message": "Hey",
                          },
            ],
      Array[
                  Object {
                          "conversationId": 1,
                          "id": 2,
                          "message": "Hey",
                          },
                   Object {
                          "conversationId": 1,
                          "id": 1,
                          "message": "Hey",
                          },
             ],
         ],

I also tried this

 useEffect(()=>{
 const x =listings.map(x=>x.id)
 console.log(x)
 },[listings])

this prints out the following:

Array [
32,
33,
29,
15,
27,
25,
26,
4,
17,
]

I just now need to check for the specific conversation before adding my msg object to it.


回答1:


Try to create youkeyExtractor like

keyExtractor={(item, index) => index.toString()}



回答2:


You already have a variable listing and it is conflicting at keyExtractor.

change it like this

keyExtractor={(item) => item.id.toString()}


来源:https://stackoverflow.com/questions/65769926/react-native-inserting-new-object-inside-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!