Search code examples
reactjsreact-hooksreact-datepicker

Iterating through JSON and adding to array, but preventing multiple additions to the array


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);  
}

Solution

  • 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.