Home > Enterprise >  Why is my function not dispatching in react component?
Why is my function not dispatching in react component?

Time:12-24

why is fetchReviews not fetching? Originally didn't use fetchData in use effect. Ive tried using useDispatch. BusinessId is being passed into the star component. no errors in console. please let me know if theres other files you need to see. thank you!

star component:

import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import {AiFillStar } from "react-icons/ai";
import { fetchReviews } from '../../actions/review_actions';

function Star(props) {
    const [rating, setRating] = useState(null);
    // const [reviews, setReview] = useState(props.reviews)

    // const dispatch = useDispatch();

    useEffect(() => {
        const fetchData = async () => {
            await fetchReviews(props.businessId)
        };
        fetchData();
        console.log(props);
        // getAverageRating();
    });

    const getAverageRating = () => {
        let totalStars = 0;
        props.reviews.forEach(review => {totalStars  = review.rating});
        let averageStars = Math.ceil(totalStars / props.reviews.length);
        setRating(averageStars);
    }
    return (
        <div className='star-rating-container'>
            {Array(5).fill().map((_, i) => {
                const ratingValue = i   1;
                return (
                    <div className='each-star' key={ratingValue}>
                        <AiFillStar
                                className='star'
                                color={ratingValue <= rating ? '#D32322' : '#E4E5E9'}
                                size={24} />
                    </div>
                )
            })}
        </div>
   );
};

export default Star;

star_container:

import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Star from "./star";
import { fetchReviews } from "../../actions/review_actions";

const mSTP = state => {
    return {
        reviews: Object.values(state.entities.reviews)
    };
}

const mDTP = dispatch => {
    return {
        fetchReviews: businessId => dispatch(fetchReviews(businessId))
    };
};

export default connect(mSTP, mDTP)(Star);

console image

why is fetchReviews not fetching? Originally didn't use fetchData in use effect. Ive tried using useDispatch. BusinessId is being passed into the star component. no errors in console.

edit!***

made some changes and added useDispatch. now it wont stop running. its constantly fetching.

function Star(props) {
    const [rating, setRating] = useState(null);
    const [reviews, setReview] = useState(null)

    const dispatch = useDispatch();

    useEffect(() => {
        const fetchData = async () => {
            const data = await dispatch(fetchReviews(props.businessId))
            setReview(data);
        };

        fetchData();
        // console.log(props);
        // getAverageRating();
    }), [];

CodePudding user response:

ended up just calling using the ajax call in the useEffect.

  useEffect(() => {
    const fetchReviews = (businessId) =>
      $.ajax({
        method: "GET",
        url: `/api/businesses/${businessId}/reviews`,
      });

      fetchReviews(props.businessId).then((reviews) => getAverageRating(reviews));

  }), [];

if anyone knows how i can clean up and use the dispatch lmk. ty all.

CodePudding user response:

useEffect(() => {
        const fetchData = async () => {
            const data = await dispatch(fetchReviews(props.businessId))
            setReview(data);
        };    
        fetchData();
        // console.log(props);
        // getAverageRating();
    }), [];

dependency array is outside the useEffect. Since useEffect has no dependency option passed, function inside useEffect will run in every render and in each render you keep dispatching action which changes the store which rerenders the component since it rerenders code inside useEffect runs

// pass the dependency array in correct place
useEffect(() => {
        const fetchData = async () => {
            const data = await dispatch(fetchReviews(props.businessId))
            setReview(data);
        };    
        fetchData();
        // console.log(props);
        // getAverageRating();
    },[]), ;

Passing empty array [] means, code inside useEffect will run only once before your component mounted

  • Related