Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React component data not saved when submit

Below is my code, the React app is connected to Node js and the data of comment are saved when submit but it’s not working for StarRating component.
The comment data is saved in the db table but not the rating

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please pass setRating in starComponent as props

Like below:

<StarRating value={rating1} updateRating={(e) => setRating1(e)}
  onChange={e => setRating1(e.target.value)}></StarRating>

Now you will get updateRating as props in starComponent. So update rating form star component like below:

import React, { useState} from "react";
import { FaStar } from 'react-icons/fa';
const StarRating = ({updateRating}) =>{ // Here you will get setRating state(State of app component) in props

const [rating, setRating] = useState(null); // not needed this state here. Update rating value in state which comes form props
const [hover, setHover] = useState(null);
return <div>
    
    <p>Rate your experience from 0 to 5 stars</p>
    {[... Array(5)].map((star, i)=>{
        const ratingValue= i + 1;
        return (
            <label>
                <input 
                type="radio"
                name="rating" 
                value={ratingValue}
                onClick={() =>updateRating(ratingValue)} /> // Update `updateRating` state which comes from app component. 
                <FaStar 
                className="star" 
                color={ratingValue <= (hover || rating) ? "#11C4B0" : "#D3D3D3"}
                size={40}
                onMouseEnter={() =>setHover(ratingValue)}
                onMouseLeave={() =>setHover(null)}
                />

            </label>

        );
    })}

    
    </div>
    
  }
  export default StarRating;

You will get updated state in rating1 in app component if any changes occurred from starComponent.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading