Home > Software engineering >  How do I keep setState() from stringifying my array?
How do I keep setState() from stringifying my array?

Time:01-06

I have a function, eventQuery which fetches data from a Firebase DB. I am able to see the data is successfully pulled and returns what I understand to be an array of arrays each composed of a string and an object. First, my code:

  const [activeDate, setActiveDate] = useState(new Date())
  const [existingEvents, setExistingEvents] = useState({})

  useEffect(() => {
    eventQuery(activeDate)
      .then(data => {
        setExistingEvents(data);
        console.log(data)
      })
      .then(setExistingEvents(''))
      .catch(err => console.log('no events'))
  }, [activeDate])

  useEffect(() => {
    console.log('existingEvents equals: '   existingEvents)
  }, [existingEvents])

The output of console.log(data) within the promise yields something in the form of:

[["String1.1", {"String1.2": "String1.3", "String1.4": "String1.5", "String1.6": "String1.7"], ["String2.1", {etc.}], ["String3.1", {etc.}]]

However, when I use setExistingEvents(data) to pass that array of arrays to existingEvents, and then I subsequently console log the new value, the result is:

existingEvents equals: String1.1,[object Object],String2.1,[object Object],String3.1,[object Object]

As far as I can tell, setState() is essentially running toString() on my array of arrays. Am I doing something wrong or is this an inherent part of the function? Thanks so much for your help.

CodePudding user response:

Your console.log statement is actually the reason why the output looks like existingEvents was stringified (setState doesn't stringify the argument).

Instead of:

  useEffect(() => {
    // `existingEvents` is coerced to a string
    console.log('existingEvents equals: '   existingEvents)
  }, [existingEvents])

It should be:

  useEffect(() => {
    console.log('existingEvents equals:', existingEvents)
  }, [existingEvents])

Also, your second .then() function should be:

.then(() => setExistingEvents('')) // not .then(setExistingEvents('')) <- this causes setExistingEvents('') to be called immediately

CodePudding user response:

Your problem is you're using a string append on this

console.log('existingEvents equals: '   existingEvents)

If you want to have entire data in a string format, you can use JSON.stringify

console.log('existingEvents equals: '   JSON.stringify(existingEvents))

Or use a separator , in console.log

console.log('existingEvents equals: ', existingEvents)
  • Related