2

I have a small project, to fetch image from unsplash, even I check many times, I still have one problem in my code, I am running my code, but it is always give this error, but I don't get it. Any idea will be appreciated.

Mainboard.js

import React from 'react';
import styled from 'styled-components';
import Pin from './Pin';
function Mainboard(props) {
let { pins } = props; 
return (
    <Wrapper>
        <Container>
            {pins.map((pin, index) => {
                let {urls} = pin;
              return <Pin key={index} urls={urls}/>
            })}   
        </Container>
    </Wrapper>
  )}
 export default Mainboard;

Pin.js:

import React from 'react';
import styled from 'styled-components';

function Pin(props) {
let { urls } = props;
return (
    <Wrapper>
    <Container>
     <img src={urls?.regular} alt="pin"/>
    </Container>
 </Wrapper>
)}
export default Pin;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Can you show the code of where Mainboard is being used? – tcf01 Feb 24 '21 at 08:20
  • 2
    Some item in `pins` array is undefined and `let {urls} = pin` will throwing an error. Try with `let { urls } = pin ?? {}` – adiga Feb 24 '21 at 08:22
  • @tsecheukfung01 here https://stackoverflow.com/questions/66346595/react-hook-useeffect-has-a-missing-dependency-getnewpins/66346693#66346693 –  Feb 24 '21 at 08:46

1 Answers1

0

I don't think the main issue is destructing from an undefined object (this is only a symptom), but more that you have "holes" in your data, i.e. your array has undefined elements in it.

If there is an undefined element in your pins array then perhaps you should filter them first before mapping. A quick way is to apply a Boolean constructor against the truthy defined values and the falsey undefined values, i.e. arr.filter(Boolean).

function Mainboard({ pins }) {
  return (
    <Wrapper>
      <Container>
        {pins.filter(Boolean).map((pin, index) => {
          const {urls} = pin;
          return <Pin key={index} urls={urls}/>
        })}   
      </Container>
    </Wrapper>
  );
}

Of course you should try to ensure your data array is properly maintained in the first place so "holes" aren't introduced. If you add how Mainboard is rendered, what the props values are that are passed to it we may be better able to help optimize.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • App.js here for Mainboard.js, https://stackoverflow.com/questions/66346595/react-hook-useeffect-has-a-missing-dependency-getnewpins/66346693#66346693 –  Feb 24 '21 at 08:45