CHIU TZE CHEUNG
CHIU TZE CHEUNG

Reputation: 101

TypeError: Cannot read properties of undefined (reading 'split') in react

Here is my code.I'm using an API call in useEffect just like following:

    const [data, setData] = useState([]);

    const getQuotationById = async () => {
        const resp = await axios.get(`${process.env.REACT_APP_API_URL}quotation-details/${id}`);
        setData(resp.data);
    };

    useEffect(() => {
        getData().catch((e) => {
            console.log('error');
            console.log(e);
        });
    }, []);

return <div>
 {data.quantities.split('/').map((quantity, index) => (<span>quantity</span>)
</div>

The interesting thing is that an error TypeError: Cannot read properties of undefined (reading 'split') in react always comes out.

But there is no error if I use the optional chain in the return sytanx like:

return <div>
 {data.quantities?.split('/').map((quantity, index) => (<span>quantity</span>)
</div>

Why this happens?

Upvotes: 1

Views: 9889

Answers (1)

Denver Shan
Denver Shan

Reputation: 106

As your code, it could be two reasons.

  1. In the first time the code executes, there could be no data assigned to the data property.
  2. If this is the same component, you are using the data from props. If you are not passing the props, it will be undefined. Or you want to use the data in the same component remove props.data and just use data.

Upvotes: 2

Related Questions