skip to Main Content

I am having the following code:

const [FishClass, setFishClass] = useState({});
//...

useEffect(() => {
  axios.get("/api/v1/class/" + params.id).then(
    (response) => {
      console.log("axios call: " + response.data);
      if (Array.isArray(response.data)) {
        setFishClass(response.data[0]);
      } else {
        setFishClass(response.data);
      }
    },
    (error) => {
      console.log(error);
    }
  );
}, []);

Two things are strange first setFishClass does not set the Object correctly. Second the Object sometimes seems to be an Array… What am i doing wrong and how can i solve this more elegant?

2

Answers


  1. You have to understand better what response.data can look like.

    From what I understood response.data can be either an array or an object and based on that you set your FishClass state. cool and your code should work for that.

    however, you said that FishClass is sometimes an array. this can only happen when response.data is an array and and response.data[0] is an array: [[{..}]]
    so I think that you have to check with response.data[0] instead of response.data.
    my guess is that the endpoint is always returning an array, and it is either [{..}] of [[{..}]]

    useEffect(() => {
      //...
      if (Array.isArray(response.data[0])) {
        setFishClass(response.data[0]);
      } else {
        setFishClass(response.data[0][0]);
      }
      //...
    }, []);
    
    Login or Signup to reply.
  2. if you are not confirmed which data type the response data will be
    you can simply modify your code. first set the data and then when you are using it for your specific use case then apply the conditions or destructure it.

      useEffect(() => {
      const fetchData = async () => {
        try {
          const response = await axios.get("/api/v1/class/" + params.id);
          setFishClass(response?.data);
        } catch (error) {
          console.log(error);
        }
      };
    
      fetchData();
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search