简体   繁体   中英

React state (useState) doesn't update with fetched data

Background
I have a star rating system. When a user has already rated the content, I want them to be able to see their previous rating when the page loads.

I am able to fetch the rating data for the user and I have a set initial state for the star rating, just in case there isn't any rating yet.

The Goal
The goal is to set the initial state for the star rating with a value of 0 . When the previously-stored rating value is fetched, I want the initial state value to update to the fetched rating value.

The Problem
Currently, when the page loads, the star rating value says it's undefined , even though the stored rating value is fetched and appears in my console. I'm pretty sure this is happening because the variable is being called before the data query has finished. Unfortunately, it doesn't update when it does finish.

Code

In the code below, articleRating is the fetched rating value

// data query
const {
    data: { feedback, id: feedbackId, rating: articleRating },
    status: feedbackStatus,
  } = useGetFeedback(slug as string, "lesson")

// setting initial state for star rating
const [starsSelected, selectStar] = useState(0)

// Updating the rating value to show previously stored rating
useEffect(() => {
    if (articleRating !== null || articleRating !== "undefined") {
      console.log("rating value: ", articleRating)
      selectStar(articleRating)
    }
 }, [])

In the code above, I'm using the useEffect hook because I get an error message saying there are infinite renders without it and the page breaks.

Thanks in advance for any advice! ✌️

您的useEffect仅在第一次渲染时运行,您应该将articleRating添加到第二个参数中的依赖项数组,然后它只会在该变量更新时运行。

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