0

I have an array that I get from a hook - the playlists and a trying to put it in the state, in the playlistsLocal, but it seems that my state variable is still empty when I view it in the console. I know that setting the state is asynchronous and that kind of stuff but it is really that challenging to set the state? Sorry maybe I am doing something wrong can you guys have a look please

import React, { useState, useEffect } from 'react'
import { useStoreState, useStoreActions } from 'easy-peasy'
import { Select } from 'antd'

function PlaylistSelector() {
    const playlists = useStoreState(state => state.playlists.items)
    const reloadPlaylists = useStoreActions(actions => actions.playlists.reload)
    const [playlistsLocal, setPlaylistsLocal] = useState(null)

    useEffect(() => {
        reloadPlaylists()
        setPlaylistsLocal(playlists);
    }, [playlistsLocal])

    var el = <Select style={{ width: '100%' }} defaultValue={playlistsLocal[0]?.name}>
        {playlists.map((e, key) => {
            return <option key={key} value={e.value}>{e.name}</option>;
        })}
    </Select>
    console.log('playlistsLocal ', playlistsLocal);
    return el
}

export default PlaylistSelector
Cristian Sfetcu
  • 153
  • 1
  • 8
  • I think the array passed to your effect should be `[playlists]` instead of `[playlistsLocal]`. By the way, I don't know why you reload the playlist into your effect. – Olivier Boissé Sep 26 '21 at 20:13
  • tried with ```[playlists]``` also but it went into a loop. i want this because i need to relad the playlists to have them available from the model – Cristian Sfetcu Sep 26 '21 at 20:32
  • Are you sure that `useStoreState()` returns the same object each time called? – Gieted Sep 26 '21 at 20:39
  • Why are you duplicating state? This is generally anti-pattern in React. You are using the `defaultValue` prop on the `select` element so it's not like you can change it on a subsequent render anyway. – Drew Reese Sep 26 '21 at 22:10
  • What does your easy-peasy store model look like? – JAM Sep 30 '22 at 11:50

0 Answers0