Dhanush
Dhanush

Reputation: 49

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?

Upvotes: 1

Views: 1384

Answers (2)

Henry Le
Henry Le

Reputation: 451

I think before the load product, the value of your product is null or {}, so when you use product.description the value will be undefined. You can use:

const substrings = (product?.description || '').split(".");

Upvotes: 1

Topliceanu Razvan
Topliceanu Razvan

Reputation: 51

I think the problem here is the way you declared the product using useState. For the second part you declare the description directly so when you split it, it might be an empty string or whatever you declared it, but not undefined.

But for the first part, you declare just the product variable, without the description property. So before fetching, when you try to split product.description, it is undefined and becomes a value just after fetching.

In order to fix it you might declared the product like this:

const [product, setProduct] = useState({ description: "" }) or just simply use ? operator like this: const substrings = product.description?.split(".");

Also there might be a problem because you first declare substrings as an empty array and then you declare it again as a const.

Upvotes: 1

Related Questions