Home > database >  React creating JSX from state showing error
React creating JSX from state showing error

Time:04-20

In my react application, on page load, I am calling an API and storing that value in the state. When I try to create a JSX element from the state I am getting the error Cannot read properties of undefined (reading 'expire').

const [domains, setDomains] = useState([]);
const [records, setRecords] = useState({});

useEffect(() => {
        axios.get('zones/domains').then((res) => {
            setDomains(res.data)
            axios.get('zones/records', {
                params: {
                    l_id: res.data[0].l_id
                }
            }).then((res) => {
                setRecords(res.data)
            });
        });
        
    }, [])


let table_str = <tr>
    <td>SOA</td>
    <td>{records.added.expire}</td>
    <td>{records.added.value1} {records.added.value2}</td>
</tr>

CodePudding user response:

Your states are empty before the axios call. Make sure to update as follows with optional changing.

let table_str = <tr>
    <td>SOA</td>
    <td>{records?.added?.expire}</td>
    <td>{records?.added?.value1} {records?.added?.value2}</td>
</tr>
  • Related