Marco
Marco

Reputation: 161

How use useSelector and useDispatch properly with redux-thunk?

Somebody can explain me, how I get wrong? How use useSelector and useDispatch properly with redux-thunk async function in useEffect.

My output of code return only the "User list" title on screen and not the list of users that I expect.

The code:

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchUsers } from '../redux'

function UserContainer() {
    const userData = useSelector(state => state.user)
    const dispatch = useDispatch()

    useEffect(() => {
        dispatch(fetchUsers())
    },[dispatch])

    return userData.loading ? ( <h2>Loading...</h2> ) :
        userData.error ? (<h2>{userData.error}</h2>) :
        <div>
            <h2>User List</h2>
            <div>
                { userData && userData.users && userData.users.map(user => <p>{user.name}</p>) }
            </div>
        </div>

 }

 export default UserContainer

Here the action function:

export const fetchUsers = () =>{
    return function(dispatch) {
        dispatch(fetchUsersRequest())
        axios.get('https://jsonplaceholder.typicode.com/users')
        .then(response => {
            const users = response.data
            dispatch(fetchUsersSuccess(users))
        })
        .catch(error => {
            dispatch(fetchUsersFailure(error.message))
        })

    }
}

Upvotes: 2

Views: 5431

Answers (1)

Marco
Marco

Reputation: 161

I FOUND THE ERROR! It was an oversight. In the action function I .map() the response where it's not needed:

const users = response.data .map(user => user.id)

Well, this code is a perfect example about How use useSelector and useDispatch properly with an ajax call with redux-thunk.

Upvotes: 1

Related Questions