Cannot Read Property 'split' of Undefined in the below code

Why split property is undefined here? I fetched the products from my product api through axios, I received json data that have some properties(name,description,…)

const [product, setProduct] = useState({});
let substrings=[];
  useEffect(() => {
    const getProduct = async () => {
      try {
        const res = await axios.get(`/products/${props.match.params.id}`);
        setProduct(res.data);
     
      } catch (error) {
        console.error(error);
      }
    };
    getProduct();
    //eslint-disable-next-line
  }, []);
  
  const substrings = product.description.split(".");

This is the json that we get from products/id
{"_id":"1","name":"Mangoes","image":"https://drive.google.com/thumbnail?id=1Iq2F4fYxDi7HdX-IJcRuON-CbNuK-pxd","description":"This sweet and fresh mangoes make your day sweet","category":"Fruits","keywords":"fruits","price":120,"countInStock":0,"content":""}

whereas it works fine here

const [product, setProduct] = useState({});
const [desc,setDesc]=useState("");
  useEffect(() => {
    const getProduct = async () => {
      try {
        const res = await axios.get(`/products/${props.match.params.id}`);
        setProduct(res.data);
        setDesc(res.data.description);
      } catch (error) {
        console.error(error);
      }
    };
    getProduct();
    //eslint-disable-next-line
  }, []);
  
  const substrings = desc.split(".");

Can anyone tell us why is it so?

22 thoughts on “Cannot Read Property 'split' of Undefined in the below code”

Leave a Comment