简体   繁体   中英

Javascript find() array method is returning undefined. what am I doing wrong?

On the click of a button. I am dispatching the id to my resellerSlice so that I can be able to use.find() and select the exact array object that has the same id as my id

const handleDetailsModal = (e) => {
 
     setResellersId(e.currentTarget.id)
 
     dispatch(uiAction.toggle())
     dispatch(
         toggleResellers (resellersId)
     )
 
 }

On getting to the resellerSlice

    const resellerSlice = createSlice({
        name: 'reseller',
        initialState,
        reducers: {
            toggleResellers(state, action) {
                const resellerId = action.payload;
                const clickedReseller = state.resellers?.find((reseller) => reseller.id === resellerId);
    
                console.log(clickedReseller) //returns undefined(this is the problem)
    
              
            }
          
        }
    })

What am I doing wrong?

I need the const 'clickedReseller' to contain the properties of object that its Id is the same as the 'resellersId', So I can use the object.

Here's my initial state

const initialState = [
    {
        resellerName: 'xxxx xxxx',
        id: 1,
        resellerLimits: [
            {
                USD: 700,
                GBP: 200,
                EURO: 990,
            }
        ],
        paymentMethods: [
            'wirePay',
            'flux',
            'bankTransfer'
        ],
        totalTransactions: 0,
        rating: 0,
    },

This is what the objects inside the array looks like

So, I finally figured it out.

My resellerId was actually a string and not an integer.

I discovered this after doing a typeOf() on it.

So instead of using the === comparison operator I used == and it worked out.

Thanks guys

Normally, the state of your reducer is alreay the state.resellers as demonstrated in the redux toolkit documentation , so you can do directly state.find(reseller => reseller.id === resellerId) !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM