'TypeError: Cannot read properties of undefined from API fetch

const [address, setAddress] = useState("")
const [neighborhood, setNeighborhood] = useState("")
const [city, setCity] = useState("")
const [state, setState] = useState("")

const searchZIP = async(zip) => {
    zip = zip.replace(/\D/g, "")
    const data = await fetch(`http://viacep.com.br/ws/${zip}/json/`)
        .then(data => data.json())
        .catch(() => {
            setAddress("--")
            setNeighborhood("--")
            setCity("--")
            setState("--")
        })
    const { logradouro="--", bairro="--", localidade="--", uf="--" } = data 

The error is ocurring when it tries to read this last line (reading: 'logradouro') for a invalid ZIP input even though I assign "--" as a default value.

    setAddress(logradouro)
    setNeighborhood(bairro)
    setCity(localidade)
    setState(uf)

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source