简体   繁体   中英

How to use useState with React-redux-firebase to re-render

I'm exploring hooks with react-redux-firebase but my "setDataProducts" is behaving oddly. I'm using useEffect() like I could use componentDidMount() but not sure if this is the right way.

export default function ProductList() {
    const [dataProducts, setDataProducts] = useState([]);
    const firestore = useFirestore();

    const fetchProducts = async () => {
        const response = firestore.collection("products");
        const data = await response.get();

        data.docs.forEach((product) => {
            setDataProducts([...dataProducts, product.data()]);
            console.log(product.data());
        });
    };

    useEffect(() => {
        fetchProducts();
    }, []);

    return (
        <div>
            {isLoaded &&
                dataProducts.map((product) => {
                    return (
                        <div>
                            <h4>{product.title}</h4>
                            <h3>{product.price}</h3>
                        </div>
                    );
                })}
        </div>
    );
}

I cannot render the both products I have in Firestore. Only One is rendering... So I dont understand. Should not it rerender when state is updated?

Thanks for reply

We can see there was not rerendering

I think it is because you called setDataProducts again before dataProducts updated.

Please replace fetchProducts method with my code following:

const fetchProducts = async () => {
  const response = firestore.collection("products");
  const data = await response.get();

  const newProducts = data.docs.map((product) => product.data());
  console.log(newProducts);
  setDataProducts([...dataProducts, ...newProducts]);
};

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