Home > Back-end >  How to pass boolean value from the API response to child component
How to pass boolean value from the API response to child component

Time:11-10

I'd like to pass boolean from API Java response object to child component. What can I change to use isFavourite value in the child component? The main question is how to pass boolean values to other components. Currently, I receive an undefined value on isFavourite.

RESPONSE

  {"id":12,"title":"The Lord Of The Rings","isUserFavourite":true}

Movie

    const Movie = ({match}) => {
    const [movie, setMovie] = useState([]);

    useEffect(
        () =>
            fetch(`http://localhost:8080/api/movie/fetch/${match.params.id}`, {
                    headers: {
                        "Content-Type": "application/json",
                    },
                })
                .then((response) => {
                    return response.json();
                })
                .then((data) => {
                    setMovie(data);
                }),
        []
    );

    return (
      <div>
            <h2>{ad.title}</h2>
            <FavouriteButton id={movie.id} isUserFavourite={movie.isUserFavourite}/>
        </div>
    );
};
export default Ad;

Favourite button

    const FavouriteButton = (props) => {
    const [isFavourite, setIsFavourite] = useState(props.isUserFavourite);


    const onClickHandler = () => {
        const requestOptions = {
            method: "PATCH",
        };
        fetch(`http://localhost:8080/user/favourite/${props.id}`, requestOptions).then(
            setIsFavourite(prevState => !prevState));
        ;
    }
    return <div>{isFavourite ? (<p>FAVOURITE</p>) : (<p>NOT-FAVOURITE</p>)}
        <button onClick={onClickHandler}>FAVOURITE/NOT-FAVOURITE</button>
    </div>
}

export default FavouriteButton;

CodePudding user response:

You are rendering the component before the API is finished hence the state inside the child component is being initialized as 'undefined' before the API call is done, try to add a loader or a condition to check if the API is not finished yet don't render the component FavouriteButton

  • Related