0

I am fetching an object from api using axios.get("url"). The object fetched successfully (in Animal state) but there is a component level state (imageState) which requires updation using setState with fetched data.
Code:
Component:

import React,{useEffect, useState} from 'react'
import axios from 'axios'
const AnimalDetail = ({match}) => {
    const [Animal ,setAnimal ] = useState({})
    const Id = parseInt(match.params.id)
    const [imageState, setImageState] = useState ("");
 
useEffect(()=>{
            const fetchAnimal = async () => {
                const {data} = await axios.get(`/api/animals/${Id}`)
                setAnimal(data)
            }
            fetchAnimal()
            // setImageState(Animal.image[0])   // need to access first index of image object
    },[])

    useEffect(()=>{

   setImageState(Object.values(Animal.image)[0])  // error cant convert undefined to object
}
   
    return (
        <>
       <h2>imageState </h2>  //undefined
        <h2>{typeof(Animal.image)}</h2>  //gives object
       </>
  )
}
export default AnimalDetail


Backend Api :

{"id":2,
"image":["/image.jpg","/image2.jpg"],
"price":60000,
"breed":"",
"isAvailable":true,
"weight":110,
}

How can i fetch the data and update the component level state periodically(after fetching)?

6
  • Can you console.log(data) and edit your post to tell me what you get? Commented Apr 12, 2021 at 18:36
  • 1
    It looks like you declare imageState a second time after your useEffect. This is not the main problem, but you will need to delete that line eventually. Commented Apr 12, 2021 at 18:36
  • Is there a compelling reason not to do setImageState(data.image[0]) inside fetchAnimal? Commented Apr 12, 2021 at 18:37
  • @samuei yes there is no problem is doing that too. The real problem still here with me is the typeof(Animal.image) that gives object but when i just console.log(Animal.image) then i get Array ["img1",''img2"]. I actually need to map these images into divs. Commented Apr 12, 2021 at 21:30
  • 1
    @MichaelHoobler I assigned {data} to component state(Animal) and when i console.log(Animal) i get an object in console like this Object { id: 1, image: (1) […], breed: "", isAvailable: true, weight: 100, … }. Commented Apr 12, 2021 at 21:36

2 Answers 2

3

You can try following, maybe this can help you. Removed the second useEffect and updated the image state in the first useEffect.

And also I can see, you have declared const [imageState, setImageState] = useState (""); twice. You can remove the second one.

Also, make sure you handle the API error in useEffect otherwise this may break the application on API failure.

import React, { useEffect, useState } from 'react';
import axios from 'axios';
const AnimalDetail = ({ match }) => {
  const [Animal, setAnimal] = useState({});
  const Id = parseInt(match.params.id);
  const [imageState, setImageState] = useState('');

  useEffect(() => {
    const fetchAnimal = async () => {
      const { data } = await axios.get(`/api/animals/${Id}`);
      setAnimal(data);
      setImageState(data.image[0]);
    };
    if (Id) {
      fetchAnimal();
    }
  }, [Id]);

  return (
    <>
      <h2>imageState </h2> //undefined
      <h2>{typeof Animal.image}</h2> //gives object
    </>
  );
};
export default AnimalDetail;
Sign up to request clarification or add additional context in comments.

Comments

2

your code has some error in the second useEffect. you can use this one :

     useEffect(() => {
if (Animal) setImageState(Object.values(Animal.image)[0]); // error cant convert undefined to object
      }, [Animal]);

this is because the Animal should have value first. and you are defining imageState two times in your code! the first one is enough.

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.