Reputation: 1131
index.js
const [questionRepliesAll, setQuestionRepliesAll] = useState([])
const [questionReplies, setQuestionReplies] = useState({
replies: [
{
desc: 'hello word 1'
},
{
desc: 'hello word 2'
}
],
reply_users: [
{
user: 1
},
{
user: 2
}
]
})
questionReplies.replies.map((reply, i) => {
setQuestionRepliesAll([...questionRepliesAll, {'reply': desc, user_id: questionReplies.reply_users[i].user])})
results
[{reply: 'hello word 1', user_id: 1}, {reply: 'hello word 2', user_id: 2}] // expected
[] // actual result
first implementation
const combined = questionReplies.replies.map((reply, i) => {
return {'reply': desc,
user_id: questionReplies.reply_users[i].id}
})
setQuestionRepliesAll(combined)
Basically, I want to combine 2 arrays into 1 and add it to questionRepliesAll, i tried adding it with just assigning the combined array to a variable ahnd then setting it setQuestionRepliesAll(combined)
but that threw errors when i tried using .map() which was Objects are not valid as a React child
, go down below to see what I tried doing at first, any help is appreciated!
Upvotes: 1
Views: 169
Reputation: 2695
I would recommend using a for loop
for this functionality.
let arr = {
replies: [
{
desc: 'hello word 1'
},
{
desc: 'hello word 2'
}
],
reply_users: [
{
user: 1
},
{
user: 2
}
]
}
let formattedArray = [];
for(i=0;i<arr.replies.length;i++){
formattedArray.push({reply:arr.replies[i].desc,user:arr.reply_users[i].user})
}
console.log(formattedArray)
Implementation in your case :
import {useEffect, useState} from 'react';
export default function App() {
const [questionRepliesAll, setQuestionRepliesAll] = useState([])
const [questionReplies, setQuestionReplies] = useState({
replies: [
{
desc: 'hello word 1'
},
{
desc: 'hello word 2'
}
],
reply_users: [
{
user: 1
},
{
user: 2
}
]
});
useEffect(()=>{
let formattedArray =[]
for(var i=0;i<questionReplies.replies.length;i++){
formattedArray.push({reply:questionReplies.replies[i].desc,user:questionReplies.reply_users[i].user})
}
setQuestionRepliesAll(formattedArray);
},[questionReplies])
return (
<div>
<ul>{questionRepliesAll.map((item,key)=><li>user {item.user} , reply : {item.reply}</li>)}</ul>
</div>
);
}
Upvotes: 1