Search code examples
reactjsreact-hooksjavascript-objectsuse-effect

TypeError: can't convert undefined to object, using React


I'm not able to set the data into react state variable. It's showing me that object is undefine.

I know it's illegal to pass an object as a child of a component. Is there any way I can get data from nested object. Here I'm using Recursion,but no luck.

// API Call
const fetchData = async () => {
  try {
    const response = await axios.get(
      "https://60d007f67de0b200171079e8.mockapi.io/bakery"
    );
    
    console.log('fetched data', response.data) // able to fetch the Data

    return response.data;
  } catch (err) {
    console.error(err);
  }
};


const extractData = (objects) => {
  const objectKeys = [];
  
  const values = Object.values(objects) // Object is undefine

  values.forEach(val => 
    val && typeof val === "object" ? extractNestedData(val) : objectKeys.push(val))
    
  return objectKeys;
  
}
const extractNestedData = (objects) => {
  const object = objects[0];
  const data = []
  data = extractData(object)
  return data;
}

export default function App() {
  const [bakery, setBakery] = useState([])
  const [flatBakery, setFlatBakery] = useState([])

  useEffect(() => {
    
    let mount1 = true;
    if(mount1){
      
    fetchData().then((randomData) => {
      setBakery(randomData)
      console.log('bakery', bakery) // not able to set the data.

    })
  }
  
  return () => { mount1 = false;}
  
  }, []);
  
  useEffect(() => {
    let mount2 = true;
    
    if (mount2) {
      
      setFlatBakery(extractNestedData(bakery));
    }
    
    return () => mount2 = false;
    
  }, [bakery])
  
  return (
    <div>
      Hello
    </div>
  );
}

Output enter image description here

I'm struggling to fetch the data from Nested objects in React.


Solution

  • That's because bakery is an empty list initially. You should only call extractNestedData after bakery data has been fetched.

    Here's the updated code:

    // API Call
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "https://60d007f67de0b200171079e8.mockapi.io/bakery"
        );
    
        console.log("fetched data", response.data); // able to fetch the Data
    
        return response.data;
      } catch (err) {
        console.error(err);
      }
    };
    
    const extractNestedData = (objects) => {
      const objectKeys = [];
    
      const values = Object.values(objects);
    
      values.forEach((val) =>
        val && typeof val === "object"
          ? extractNestedData(val)
          : objectKeys.push(val)
      );
    
      return objectKeys;
    };
    
    export default function App() {
      const [bakery, setBakery] = useState([]);
      const [flatBakery, setFlatBakery] = useState([]);
    
      useEffect(() => {
        let mount1 = true;
        if (mount1) {
          fetchData().then((randomData) => {
            setBakery(randomData);
            console.log("bakery", bakery); // not able to set the data.
          });
        }
    
        return () => {
          mount1 = false;
        };
      }, []);
    
      useEffect(() => {
        let mount2 = true;
    
        if (mount2 && bakery.length > 0) {
          setFlatBakery(extractNestedData(bakery[0]));
        }
    
        return () => (mount2 = false);
      }, [bakery]);
    
      return <div>Hello</div>;
    }