简体   繁体   中英

Uncaught (in promise) Error: Rendered more hooks than during the previous render

enter image description here I'm using useEffect hook to use fetch api but it doesn't work. when there is only one api it is working fine but when i use another api to fetch data using the useEffect hook in the createData function it gives error.

I did some research and i think it is because of some issues caused in re rendering of component in react, i tried to search for the fix but couldn't find it so I'm posting it, if there is any question kindly ask me in comments I'll give more details about it.

export default function Unpaid({ transporterId, getFn }) {
  const [itemData, setItemData] = useState([]);
  const [resData, setResData] = useState([]);


  const idUrl =
    "https://url...";

  useEffect(() => {
    let mounted = true;

    fetch(idUrl)
      .then((data) => data.json())
      .then((data) => setResData(data));

    return () => (mounted = false);
  }, []);

  console.log(resData, "response data");

  const dispatchId = resData.map((item) => item.id);
  console.log(dispatchId, "dispatch id");

  function createData(
    po,
    id
  ) {
    useEffect(() => {
      fetch(
        "https://url+id"
      )
        .then((data) => data.json())
        .then((data) => setItemData(data));
    }, []);

    console.log(itemData, "yohohoho");

    return {
      po,
    };
  }

  function Row(props) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);

    return (
     <>
       jsx content
     </>
    );
  }


  const rows = resData.map((item) =>
    createData(
      item.purchase_order_details.po_number &&
        item.purchase_order_details.po_number.length > 0
        ? item.purchase_order_details.po_number
        : "NA",
     
      item.id
    )
  );
 
  return (
   <>
     jsx content
   </>
  );
}

By calling createData inside resData.map(...) , you are calling useEffect in a loop, which violates the rules for hooks . You can call hooks only on the top level.

To fix this, you should move the effect outside of createData to the top level, add the dependency resData to the and loop over resData inside the effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM