Search code examples
reactjsreact-hooksantd

AntD Rate DefaultValue Doesn't Get the Value


The defaultValue function of AntD Rate doesn't work. Or I do something wrong.

Here is my main page:

const BookPage = () => {
    ...
    const [state, setState] = useState({});

    useEffect(() => {
        fetch()
    }, [])

    async function fetch() {
        ...
        const rate = await UserBookService.fetchRate(bookId);

        await setState({..., rate: rate});
    }

My return function:

    console.log(state.rate)
    return (
        <>
            <div style={{width: "fit-content", display: "inline-block", marginLeft: "200px"}}>
            ...

                <div style={{display: "inline-block", float: "right", marginLeft: "50px", marginTop: "70px"}}>
                    ...
                    <hr/>
                    <Rate defaultValue={state.rate} onChange={(value) => onChange(value)}></Rate>
                </div>
            </div>
        </>
    )

The result of console.log(state.rate) :

undefined
undefined
5
5

So, it's probably because of the undefined lines but I don't know how to solve it.


Solution

  • Here is the solution I found, I had to change the RateSection from function component to class component. So that, I could use an if-else statement on the render method.

    import {Rate} from "antd";
    import UserBookService from "../../service/user/UserBookService";
    import React from "react";
    
    class RateSection extends React.Component {
        state = {
            rate: undefined
        }
    
        constructor(props) {
            super(props);
            this.getCurrentRate().then(value => this.setState({rate: value}));
        }
    
        getCurrentRate = async () => {
            return await UserBookService.fetchRate(this.props.bookid);
        }
    
        onChange = async (value) => {
            await UserBookService.addRate(this.props.bookid, value);
        }
    
        render() {
            if (this.state.rate !== undefined) {
                return (
                    <Rate defaultValue={this.state.rate} onChange={(value) => this.onChange(value)}></Rate>
                )
            }
        }
    }
    
    export default RateSection;