Nimrod
Nimrod

Reputation: 389

React variable value never getting used in find function

Take a look at the code below. I'm passing userId into my action but it's value is never being used. Maybe I'm using the find function in a wrong way, some help is appreciated.

export const getUserInfo = (userId) => dispatch =>{
    axios.get("http://localhost:5000/users")
    .then((res) =>{
        const userInfo = res.find((userId) =>{
            return res.data.id === userId;
        })
        dispatch({
            type: USER_INFO,
            payload:  userInfo
        })
    })
}

Edit: What I want to do is to match the res.data.id with a given userId.

Upvotes: 1

Views: 112

Answers (2)

Mvrocha
Mvrocha

Reputation: 393

The userId in find function is a scope variable, so it´s different from the one you are passing as parameter of your function. The right way to find elementId would be:

 const userInfo = res.find((element) =>{
            return element.data.id === userId;
        })

Upvotes: 1

prasanth
prasanth

Reputation: 22490

remove the userId in find function param and replace with data instead of userId

export const getUserInfo = (userId) => dispatch =>{
    axios.get("http://localhost:5000/users")
    .then((res) =>{
        const userInfo = res.find((data) =>{ //<= change the param
            return data.id === userId; // remove the res and call from data
        })
        dispatch({
            type: USER_INFO,
            payload:  userInfo
        })
    })
}

Upvotes: 1

Related Questions