why return data is not displaying?

Viewed 44

I checked with console.log the data is showing but in the main page data is not displaying, i don't understand what is wrong here , please help me thanks in advance

useEffect(() => {
  const newArr = [...messages, ...receiveMessages]
  console.log("newArr", newArr)
    newArr.map(m => 
     console.log(m.type,m.msg)
     )
}, [messages, receiveMessages]);

 
 { newArr ? newArr.map((m) => {
      return <div style={{float :'right'}}>{m.msg}</div>
  })
  : null 
  } 
2 Answers

You need to use newArr as a state variable.

const [newArr, setNewArr] = React.useState(null)
useEffect(() => {
  setNewArr([...messages, ...receiveMessages])
}, [messages, receiveMessages, setNewArr]);

You declared the newArr variable inside useEffect with const keyword, scope of this keyword is inside pair of brackets so it is undefined outside of useEffect, that is the reason why your render code returns null.

You can move the const newArr = [...messages, ...receivedMessages] out of useEffect function, it works but it is not recommended, you will got warning or linting error when use linting tool (eslint, etc.)

Best approach is store newArr as state

const [newArr, setNewArr] = React.useState([]);

useEffect(() => {
  setNewArr([...messages, ...receiveMessages])
}, [messages, receiveMessages]);
Related