0

Hello i've been trying to map this however i keep getting the error : Cannot read properties of undefined (reading 'filter') enter image description here

this is the code i'm using to fetch the data

const [data, setData] = useState([]);
const [filters, setFilters] = useState(data);

  const getProduct = async () => {
const response = await fetch(Data source (cant share it));
if(componentMounted){
  setData(await response.clone().json());
  setFilters(await response.json());
}

return () => {
  componentMounted = false;
}
}

useEffect(() => {
  getProduct()
   // eslint-disable-next-line
}, [])

and this is how i'm mapping the data:

     {filters?.list.filter((product) => product.id === id).map((product) => (
          <div className='product-bigger-wrapper'>
          
            <div class="product-list-wrapper"> 
              <div className="product-detail-container">              
                <div>                    
                  <div className="image-container">
                    <img src={product.image} className="product-detail-image" alt=""/>
                  </div>            
                </div> .... }

Please Note that everything worked fine before adding the count and the list to the api

1
  • 1
    On initial load, filters is set to data, and data is []. At which point filters?.list is undefined, because the ?. only checks filters is defined (which it is, as an empty array that doesn't have a .list property) You might want to check that .list is defined as well (filters?.list?.filter()) Commented Aug 31, 2022 at 15:08

1 Answer 1

1

You've initialized data as an array, but you're expecting an object.

It's probably best to set the default value to undefined, null, or a default object.

const [data, setData] = useState();

or

const [data, setData] = useState(null);

or

const [data, setData] = useState({count: 0, list: []});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.