Home > other >  react.js State is empty although using useEffect
react.js State is empty although using useEffect

Time:05-16

I have a problem checking the length of my state although I use axios to get data. here is what I've done so far.

code:

const getAllBanners = async () => {
    res = await axios.get(`/admin_return_banner_positions/`).then((res) => {
      setBanners(res.data.result)
    })
  }

  // HANDLING USEEFFECT
  useEffect(() => {
    getAllBanners()
  }, [])


{getBanners.hits.total.value > 0 ? <>
                    <thead>
                      <tr>
                        <th style={{ fontSize: "18px" }}>cat</th>
                        <th><span style={{ fontSize: "18px" }}>up</span><hr /><span> name</span></th>
                        <th style={{ fontSize: "18px" }}>number</th>
                        <th><span style={{ fontSize: "18px" }}>down</span><hr /><span>name2</span></th>
                        <th style={{ fontSize: "18px" }}>number</th>
                      </tr>
                    </thead> <> : null}

error:

TypeError: Cannot read properties of undefined (reading 'total')
style={{ direction: "rtl", textAlign: "center" }}
  738 | >
> 739 |   {getBanners.hits.total.value > 0 ? <>

CodePudding user response:

I believe the getBanners state has been initialised with some default value. That value might not be having nested properties up to total.

You are probably better off using optional chaining in such scenarios -

const BannerComponent = () => {
  const [getBanners, setBanners] = useState();

  const getAllBanners = async () => {
    await axios.get(`/admin_return_banner_positions/`).then((res) => {
      setBanners(res.data.result)
    });
  }

  useEffect(() => {
    getAllBanners()
  }, []);

  if (getBanners?.hits?.total?.value > 0) { // <---- optional chaining
     return (
       <>
         <thead>
            <tr>
               <th style={{ fontSize: "18px" }}>cat</th>
               <th><span style={{ fontSize: "18px" }}>up</span><hr /><span> name</span></th>
               <th style={{ fontSize: "18px" }}>number</th>
               <th><span style={{ fontSize: "18px" }}>down</span><hr /><span>name2</span></th>
               <th style={{ fontSize: "18px" }}>number</th>
           </tr>
        </thead>
      <>
    );
  }
  return null;
}

NOTE

  • I have formatted the code a little bit to understand it better.
  • If you are not aware of optional chaining, this can give you a brief introduction --> MDN
  • Related