简体   繁体   中英

React Redux fetch data before render and do a map function

//the website render before i fetch the data from redux and give me a error //TypeError: Cannot read properties of undefined (reading 'map')

const Home=()=> {

const dispatch = useDispatch();

//import the products list
const getProducts =  useSelector ((state) => state.getProducts);
const  { products,users, loading, error}= getProducts; //i fetch the data

const AllUsersData = [ ...(users.map(item => item.createdAt))];
 console.log(AllUsersData);

console.log(users);

useEffect(() => {
    dispatch(listProducts());
  }, [dispatch]);
  
return (
    <div className="home">
        <FeaturedInfo/>
        {loading ? (
        <h2>loading...</h2>
      ) : error ? (
        <h2>{error}</h2>
      ) : (
        <Chart data={AllUsersData} title="User Analytics" grid dataKey="Active User"/>
        )
      }
        <div className="homeWidget">
            <Widgetsmall/>
            <Widgetlg/>
        </div>
    </div>
)

}

export default Home

users is expected to be an array since you are using map function. You will need to either:

  1. Set a default value:
const  { products = [],users = [], loading, error} = getProducts;

OR

  1. Check if the value is defined; then do the map function:
const AllUsersData = users ? [ ...(users.map(item => item.createdAt))] : [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM