0

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();
    }), [];

5
  • Can you post how fetchReviews is defined ? Commented Dec 23, 2022 at 20:31
  • sure in actions its called using : const receiveReview = review => ({ type: RECEIVE_REVIEW, review }); export const fetchReviews = businessId => dispatch => { ReviewAPIUtil.fetchReviews(businessId) .then(reviews => dispatch(receiveReviews(reviews))) }; its using an ajax call in util file. export const fetchReviews = (businessId) => ( $.ajax({ method: 'GET', url: /api/businesses/${businessId}/reviews }) ); found path through routes Commented Dec 23, 2022 at 20:39
  • Calling that function will create and return a small object (aka, an "action"). It won't do anything else. If you want more to happen, you need to dispatch the action. Commented Dec 23, 2022 at 20:41
  • I just changed it. now it wont stop running! ill put it in description. Commented Dec 23, 2022 at 20:42
  • change your useeffect like this : useEffect(() => { ---- your code --- fetchData(); }, []); Commented Dec 23, 2022 at 21:01

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It hurts a bit to see jQuery in a React project though :)
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.