1

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.

DMQuinn
  • 59
  • 5
  • Your useEffect looks fine and is working, but you can't inspect the new state value right after calling it. The new value won't be available until the next render cycle. – pilchard Jul 27 '21 at 09:19
  • 2
    Beware that deriving state from props is generally not best practice, [details and alternatives here](https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html). – T.J. Crowder Jul 27 '21 at 09:19
  • *"I should also mention that I am being warned about tempTracks being a missing dependency inside useEffect but this leads to an infinite loop..."* Right. The warning is correct, but it doesn't realize *why* you're using `tempTracks`. You shouldn't be using it in the hook, so don't use it, and then you don't have the warning or the infinite loop. :-) To see the updated value of `tempTracks`, just log it at the top level of your component function -- it gets called again each time state or props change. – T.J. Crowder Jul 27 '21 at 09:22

1 Answers1

2

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]]))
Oleksandr Sakun
  • 452
  • 4
  • 9