0

I can't access the field from the object since it throws the following error:

TypeError: Cannot read property 'medicineId' of undefined when i try the peice of code below,

{medlist &&
  medlist.map(({medicineId, medicineName }) => (
    <li  key={medicineId} >
      <h1>{medicineName}</h1>
    </li>               
  ))
}

it gives me index.js:1 Warning: Each child in a list should have a unique "key" prop. even though the key is unique.but idk it gives me this unique key prop err cuz it is of type string.

Note that medicineId is of type string. and i tried to overcome this by changing that piece of code to,

{medlist &&
  medlist.map((med,idx) => (
    <li  key={idx} >
      <h1>{med.medicineName}</h1>
    </li>               
  ))
}

and now i dont get the warning for unique key but, there is no display of the tag med.medicineName. when i tried {console.log(med.medicineName)} it is undefined

const fetchMedicineList = () =>{
  return axios.get('http://localhost:8080/medicine')
    .then(({data})=>{
      console.log(data[0].medicineName)//this prints the medicine name.
      return data;
    })
    .catch(err =>{
      console.error(err)
    });
}
but when i tried to store the object array inside usestate,
  const [medlist, setMedlist] = useState([])or**useState([{}])**
 useEffect(() => {
        fetchMedicineList().then(medicineList=>{
            setMedlist([...medlist,medicineList]);
            
        })
        
    }, [medlist])
and i cant print or access medlist[0].medicineName ,it says **undefine** what am i doing wrong here, thanks.

2 Answers 2

1

This just checks whether array is present. So this will always be true.

[] ? true: false; //true always

So you ll have to check the length of it like this

[].length ? true: false // false

So use this

{medlist.length &&
  medlist.map(({medicineId, medicineName }) => (
    <li  key={medicineId} >
      <h1>{medicineName}</h1>
    </li>               
  ))
}
Sign up to request clarification or add additional context in comments.

Comments

0

You set the API response without spread operation in setMedlist useState.

Check this

const initailValue =[];
const apiResponse =[{
'medicineName':'abc'
}]
const neWArr = [...initailValue,...apiResponse]
console.log(neWArr[0].medicineName)

for your problem try this,

  const [medlist, setMedlist] = useState([])
  useEffect(() => {
    fetchMedicineList().then(medicineList=>{
        setMedlist([...medlist,...medicineList]);
        
    })
    
}, [medlist])

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.