Search code examples
reactjsfunctionapiaxiosundefined

REACT Props is undefined in useEffect


i'm new with Reactjs and I have a issue with it.

In my parent Component i send a prods id to child Component:

<Review id={prod.id}/>

I need Product ID to call API in child component

export default function Index(props) {
const [pagenum, setPageNum] = useState(0);
const [reviewList, setReviewList] = useState([]);

useEffect(() => {

    get(`/public/product/rate?pagenum=${pagenum}&size=4&id=${props.id}`).then((response) => {
        if (response.status === 200) {
          console.log(response.data);
          setReviewList(response.data);
        }
      });
}, [pagenum]);
return (
    <>
        Hello {props.id}
        {
            reviewList.map((review) => (
                <div>{review.id}</div>
            ))
        }
    </>
);}

But the prod.id is return undefined, so I can't call the API. I there any way to send Id to Child Component?


Solution

  • You can add id to the dependent array. (code sandbox)

    Updated code sandbox. as per your needs . Please update as per your url and params

    import React, {
      useState,
      useEffect
    } from "react";
    import "./styles.css";
    
    function Index(props) {
      const [pagenum, setPageNum] = useState(0);
      const [reviewList, setReviewList] = useState([]);
    
    
    
      useEffect(() => {
        //https://api.github.com/users/shawnquinn
        //`/public/product/rate?pagenum=${pagenum}&size=4&id=${props.id}`
        fetch(
          `https://api.github.com/users/shawnquinn?pagenum=${pagenum}&id=${props.id}`
        ).then((response) => {
          console.log("SUccess");
          if (response.status === 200) {
            console.log(response.data);
            setReviewList(response.data || []);
          }
        });
        console.log("Id, ", props.id);
      }, [props.id, pagenum]);
    
      return ( <
        >
        Hello {
          props.id
        } {
          reviewList.map((review) => ( <
            div > {
              review.id
            } < /div>
          ))
        } <
        />
      );
    }
    
    export default function App() {
      const [id, setId] = useState(0);
      return ( <
        div className = "App" >
        <
        button onClick = {
          () => {
            setId((prev) => prev + 1);
          }
        } >
        Increase Id {
          " "
        } <
        /button> <
        Index id = {
          id
        }
        /> <
        /div>
      );
    }