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

Time:10-08

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

CodePudding user response:

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) !

CodePudding user response:

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

  • Related