1

What is the best way of iterating through a JSON response, and inserting specific elements of the JSON element into an array (assuming I'm using React hooks). This is my attempt, but the issue is the first time I execute the function, I get no output, the second time, I get the intended output, and then the consequent executions keep on adding to the datelist array(size doubles every time).

const get = () => {
    fetch('/test')  
        .then(response => response.json())
        .then(data => {setDates(data)})
    setDatelist([]);
    setDatelist(datelist => [...datelist, dates.map(date => date.start["dateTime"])]);
    console.log(datelist);  
}
Celloman
  • 25
  • 4
  • I fixed the issue of doubling by resetting the datelist to an empty array before running the map function. I still run the issue where the first function execution doesn't give me an output, though. – Celloman Dec 05 '21 at 19:16

1 Answers1

0

I think what you're looking for is the useEffect hook, document. It can subscribe to a React state or props change.

Essentially, your code should be split into several parts, something like this:

// 1. I assume you have a state to maintain `dates`
const [dates, setDates] = useState([]);

const get = () => {
    fetch('/test')  
        .then(response => response.json())
        .then(data => {setDates(data)}) 
// 2. here you call `setDates` to update the state, from your description it should be working already
}

useEffect(() => {
// 3. in useEffect hook, you can subscribe to `dates` change, and do whatever you need to do here once the dependency is updated
// below is something I copied from your question, please change it based on your need
  setDatelist(datelist => [...datelist, dates.map(date => date.start["dateTime"])]);
  console.log(datelist); 
}, [dates]);

Hope this can help, please comment if you need more information.

Mark
  • 999
  • 1
  • 7
  • 15