'The given code using useselector is not fetching data

Here in functional component useSelector is not working and not fetching any images.I have also attached my codesandbox link below.

https://codesandbox.io/s/how-to-use-redux-in-your-react-app-with-axios-forked-sgzunt?file=/src/component/users.js

import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { getUsers } from "../store/actions/usersAction";

function Users(props) {
  const users = useSelector((state) => state.users);
  useEffect(() => {
    getUsers();
  }, []);

  if (!users.length) return null;

  const userData = users.map((user) => {
    return (
      <React.Fragment key={user.id}>
        <h6> {user.first_name} </h6>
        <p> {user.last_name} </p>
        <p> {user.email}</p>
        <p>
          <img key={user.avatar} src={user.avatar} alt="avatar" />
        </p>
      </React.Fragment>
    );
  });

  return <div>{userData}</div>;
}

export default Users;



Solution 1:[1]

I got a bit confused with your code. You are using a function that returns a function that takes dispatch as an argument, likely as part of a redux-thunk action creator (i.e. async actions). https://redux.js.org/tutorials/fundamentals/part-6-async-logic

You are updating your state with the users for userReducer object so your selector function should be state.users.users

I just updated with classic Js and it is working. I am trying to achieve your functionality by using nested arrow functions.

This is the working code in Classic Js.

Edit How to use redux in your react app with Axios (forked)

Solution 2:[2]

users is empty when your components mount thats why its not rendering anything, the action is called in next line.

const [data,setData] = useState([])

useEffect(()=>{ setData(users) },[users])

replace below code

if (!data.length) return null;

replace map function too.

const userData = data.map((user) => {
return (
  <React.Fragment key={user.id}>
    <h6> {user.first_name} </h6>
    <p> {user.last_name} </p>
    <p> {user.email}</p>
    <p>
      <img key={user.avatar} src={user.avatar} alt="avatar" />
    </p>
    </React.Fragment>
  );
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mchowdam
Solution 2 Nik