简体   繁体   中英

Where to destruct Object within Array from React State

before i got this problem i used redux, there this problem didnt occur. Now where i switched my approach i encountered this issue.

On my Homepage i decided to fetch the data i need and store it in the sessionStorage, then when the user clicks on a product is getting redirected to a template where i simply want to fill in the values.

Whenever i enter the Object like data.title i get undefined (I know its because useEffect runs after the render cycle). How i should proceed here?

Either i pick the values from the sessionStorage or i fetch it, please see my code for useEffect:

 useEffect(() => {
try {
  if (
    sessionStorage.length > 0 &&
    sessionStorage.getItem(title).length > 0
  ) {
    
    const nData = JSON.parse(sessionStorage.getItem(title));
    const fData = filterProd(nData, id);
    setData(() => fData);
  } else {
    fetchFiles(`http://localhost:3000/api/prods?id=${id}`, setData);
  }
} catch (error) {
  history.push('/');
}
 }, []);

There is no issue with the this approach, the Problem begins when i want to use the parsed Array/Object and destruct it. Because useEffect runs on after the render process the first time it runs it will pickup the default state which is a empty []. I receive the propper Array after it was parsed it looks like this:

[{ artcategory: "jacket" brand: "The North Face" category: "men" description: "Outdoorjacke" details: "Unterlegter Reißverschluss, Abdeckleiste, Zwei-Wege-Reißverschluss, Stickerei" folder: "newFall2020" id: "b77a14f0-fd25-11ea-95f1-ff14921ff326" photos: (3) ["/newFall2020/b7164a10-fd25-11ea-95f1-ff14921ff326-ja1.png", "/newFall2020/b71845e0-fd25-11ea-95f1-ff14921ff326-ja2.png", "/newFall2020/b77a14f0-fd25-11ea-95f1-ff14921ff326-ja3.png"] price: 291.95 rating: 0 size: (5) ["XS", "S", "M", "L", "XL"] subcategory: "clothing" title: "ZANECK JACKET UTILITY" }]

Within this Object i have an additional Array where i store the path to the images.

In the following i will return this in my Component:

 return (
<section className='prodPageWrapper'>
  <SmallProd
    c={data && data.category}
    t={data && data.title}
    p={data && data.price}
    prodCd='prodPageDesc'
    idTitle={'pdp_title'}
    idDesc={'pdp_desc'}
    idPrize={'pdp_price'}
  />
  <Swiper data={data && data} photos={data && data.photos} />
  <ShowSizes fn={pickSize} r={sizePicked} />
  <AddToBasketMobile />
  <FavButton />
  <PDPDescription />
  <PushableMain />
  {/* <div id='test'>test</div> */}
</section>
);

How i can access the Object so that i can use it and pass it and pass it further. Thanks in advance!

If I understood correctly, your problem is about trying to use an object that isn't defined just yet. If this is the case, my suggestion would be something like:

function MyComponent() {
    const [data, setData] = useState([]);    

    useEffect(() => {
       if (localStorage) {
         // parse
       }
       else {
         // fetch
       }
       setData(data)
    })

    if (!data.length) return null; // do not render if empty

    return (
        <section ... />
    )
}

This should prevent any child from using your object, plus, you can also return a spinner or loading indicator, while !data.length is true.

thanks for the suggestion first of all. I spotted the error, first of all its an Array and i entered it like an Object, so data. but instead i should do this data[0].

This actually solved it.

However thanks!

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