reactjsreact-hooksreact-props

useState of props get undefined in React


My User data include one id,userName and one password.

I am trying to send the data I have as an Object array.It goes one by one with .map annotation, but I want to send it as a whole array. Is this possible? Coming in json format from my database. I want to send my objects as an array to the User Table file. It goes undefined. How can an object array be sent as props?

function User() {


    const [userList,setUserList] = useState([])
    const [error,setError] = useState(null);

    const getAllUsers = async() =>{ 
        const a = await axios.get(BASE_URL + "/users/all")
        
        setUserList(a.data);
    }
    useEffect(()=>{
        getAllUsers()
        .then(()=>{
            console.log("Users Promise")
        })
        return(
          <div>
            {<UserTable data = {userList} />}
          </div>
        )
      }
   

UserTable.jsx

function UserTable({props}) {
  debugger
const {id,userName,password} = props;  // It comes undefined here.
    
  console.log(props)
}

Solution

  • You're looking for a prop called props:

    function UserTable({props}) {
      const {id,userName,password} = props;
      //...
    }
    

    But you're passing a prop called data:

    <UserTable data = {userList} />
    

    The names need to match. For example:

    function UserTable({data}) {
      const {id,userName,password} = data;
      //...
    }
    

    Additionally... The prop you're passing is an array:

    useState([])
    

    Arrays do not have properties called id or userName or password. If the individual objects in that array have those properties then you'd be looking to use those individual objects.

    How you use them is not really indicated in the question. But overall the point is that an array of objects is different from an object, much in the same way that a basket of apples is not an apple.

    For example, if you wanted to display these values, you could .map() over them:

    function UserTable({data}) {
      const {id,userName,password} = data;
      return (<>
        {data.map(({id,userName,password}) => (
          <div>
            {id}<br/>
            {userName}<br/>
            <em>showing passwords is a bad idea, they shouldn't even be stored in plain text in the first place</em>
          </div>
        ))}
      </>);
    }