Home > Software engineering >  How to avoid creating nested array when appending new value into an array in react js?
How to avoid creating nested array when appending new value into an array in react js?

Time:01-05

I need to avoid creating nested array whenever appending new value into an array in react js. Currently, I am reading a data from localstorage which containing string value and localStorage data keep updating the value, so I am trying to store all value from localStorage whenever any change happen but with the below code it's creating nested array . Can you please provide some solution to this ?

const [data, setData] = useState(null);
const storedData = JSON.parse(localStorage.getItem("test"));

useEffect(() => {
setData((data) => [data, storedData])

}, [storedData])

Above logic create nested array which I wanted to avoid and wanted to keep appending the string value whatever it's coming from localStorage

CodePudding user response:

You need to use the spread operator,

const [data, setData] = useState([]);
const storedData = JSON.parse(localStorage.getItem("test"));

useEffect(() => {
setData((data) => [...data, storedData])

}, [storedData])

CodePudding user response:

What you can do is, initialize the data with an empty array. Then you can use the spread Operator to get all the values of the "string" stored in array and add the newly fetched string to data. Here's code

const [data, setData] = useState([]);
const storedData = JSON.parse(localStorage.getItem("test"));

useEffect(() => {
setData((data) => [...data, storedData])

}, [storedData])

I guess this should work. You can try it

  • Related