0

I'm new to ReactJS and I have this rating stars component with a starting value of 5 stars and everytime I click on the stars it gives me the previous value.

import React, {useState} from "react";
import Rating from '@material-ui/lab/Rating';
import "./styles.css";

export default function App() {
  const [value, setValue] = useState(5);
  return (
    <div className="App">
      <Rating
          name="simple-controlled"
          value={value}
          onChange={(event, newValue) => {
            setValue(newValue);
            console.log(value);
          }}
      />
    </div>
  );
}

So in the console.log the first click (let's say I clicked on 2 stars) returns 5 the next click returns 2 stars etc...

How I can get the current value when I click on the stars (When I click on 2 stars it returns 2)?

https://i.stack.imgur.com/PixId.png

Codesandbox example : https://codesandbox.io/s/dank-sun-ysfl3?file=/src/App.js

Any help would be appreciated, thanks a lot!

1 Answers1

0

By logging value you are just logging the current state of the component, not the new state. There are two solutions:

  1. Simply use the newValue variable inside the callback
  2. Use the solution given in This question

Brief explanation: useRef generates a state reference for a particular value, making possible to access it outside the component. Example:

import React, { useRef, useState } from "react";
import Rating from '@material-ui/lab/Rating';
import "./styles.css";

export default function App() {
  const [value, setValue] = useState(5);
  // Create ref 
  const valueRef = useRef();
  // Initialize ref
  valueRef.current = value;
  return (
    <div className="App">
      <Rating
        name="simple-controlled"
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
          // Get the latest state
          console.log(valueRef.current);
        }}
      />
    </div>
  );
}
Jean JPNM
  • 391
  • 3
  • 8