Search code examples
javascriptreactjsuse-effect

updating state array from inside useEffect with passed props


I'd like to update and add to a state array from inside a useEffect hook which renders every time an event is fired from another component (and props from that component are passed to this component.) For quickness, I'll let you know that tempPlaylistTrack is an array of objects from which I'm trying to grab the first value and I am receiving it correctly from the other component. Here is the code from the component I'm having trouble with:

function Playlist({ tempPlaylistTrack }) {
    
    const [tempTracks, setTempTracks] = useState([]);

    useLayoutEffect(() => {

        !!tempPlaylistTrack && setTempTracks([...tempPlaylistTrack[0], tempTracks]);

        console.log("tempTracks", tempTracks);

    }, [tempPlaylistTrack]);  

From my reading around the subject I believe the issue may stem from it not being synchronous(?) but as a relative beginner I have really no idea where to go from here.

I should also mention that I am being warned about tempTracks being a missing dependency inside useEffect but this leads to an infinite loop when I include it. the console log from inside use Effect shows the expected behaviour after the second time the event is fired from the other component, but not the first.

Thanks in advance for any help.


Solution

  • use spreed operator for tempTracks instead of tempPlaylistTrack[0], and in case you need access previous state than will be better to use function as an argument of setTempTracks:

    setTempTracks((preState) => ([...prevState, tempPlaylistTrack[0]]))