skip to Main Content
  1. Im fetching data from api using axios.
  2. I have array of objects.
  3. I would like to fetch objects inside array.

Here is api : https://51fgc922b7.execute-api.ap-south-1.amazonaws.com/dev/productpreview?product_id=122003
enter image description here

Here is what i tried !

  useEffect(() => {
    if (props.product_id) {
      axios.
        get(`https://51fgc922b7.execute-api.ap-south-1.amazonaws.com/dev/productpreview?product_id=${props.product_id}`)
        .then((res) => {
          console.log(res.data)
          setModelData(res.data.data[0])
        })
        .catch((error) => {
          setIsErrorImage(true)
        })
    }
  }, []);

Im able to fetch data but what im trying to achive is that, there are three objects with camera objects called 0,1,2 and i want to fetch them.

2

Answers


  1. console.log(res.data) if correct ,

    setModelData(res.data)

    and in return example ;

    modelData.map((item)=> {
    return (
    <div> {item.camera.map((data)=>{
    return (
    <div> {data.camera_beta} </div>
    )
    })}
     </div>  )})
    

    this is what i want to tell

    const [modelData, setModelData] = useState([
      {
        name: 'Electronics',
        slug: 'electronics',
        count: 11,
        items: [
          { name: 'Phones', slug: 'phones', count: 4 },
          { name: 'Tablets', slug: 'tablets', count: 5 },
          { name: 'Laptops', slug: 'laptops', count: 2 },
        ],
      },
      {
        name: 'Clothing',
        slug: 'clothing',
        count: 12,
        items: [
          { name: 'Tops', slug: 'tops', count: 3 },
          { name: 'Shorts', slug: 'shorts', count: 4 },
          { name: 'Shoes', slug: 'shoes', count: 5 },
        ],
      }
     ])
    

    you have data like this.
    this way you set the data into setmodeldata in useeffect.
    in useffect after set

    console.log(modelData) and
    console.log(modelData[0])

    you can see the difference between the two.one comes in the form of an object and the other as an array.

    at most you can map them

    Login or Signup to reply.
  2. I’m not sure about your requirement but as far as I understood you just want the array of objects from the data you get. You can get that simply by traversing the object like

    const cameraData = res.data.reduce((acc,el) => [...acc, ...el.camera], [] )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search