Home > other >  React Component not rendering a passed props
React Component not rendering a passed props

Time:12-07

I'm trying to pass an array of users as a props to a component, when I change something and click save, the array is showed in the component but when I hit refresh, the array is disappeared, here is my code:

First in my App.js I'm reading an array of users from the database (works perfectly shows the list of users) :

const [users,setUsers] = React.useState([]);
React.useEffect( () => {
      async function fetchData() {
        await axios.get('/api/users/')
        .then(response => {
         setUsers(response.data);
      });
      }
        fetchData();
      }
    , []);

Then, also in App.js, I'm rendering a ListComponent that takes the users array and shows the users:

return (
     <ListComponent users={users} />
);
}

In my ListComponent after a page refresh the console.log shows an empty array []

const ListComponent = (props) => {
React.useEffect(()=>{
      console.log(props.users); // []
},[])

CodePudding user response:

When you refresh the page, the ListComponent will be remounted, and what you are logging, is the state of the component just after it is mounted, so the user array is not already fetched. If you want log it when it is fetched, you should add the user array in the dependency array of the useEffect function:

const ListComponent = (props) => {
  React.useEffect(()=>{
    console.log(props.users); // Should be an empty array first, then updated if your fetch function is working properly
  },[props.users]);
  // ...
};

If you still cannot see the user array, it means that something is not happening as expected in your fetchData function I guess.

  • Related