M
M
Martovitskiy2021-07-03 11:58:54
React
Martovitskiy, 2021-07-03 11:58:54

How to update the data in the form if the state is overwritten?

componentDidMount() {
  this.fetch();
}

fetch = () => {
  this.fetchPermissions();

};

fetchPermissions = () => {
  return api
    .get(`api/test/get`)
    .then(response => {
      this.setState({
        userData: response.data
      });
    })
    .catch(e => {
      this.setState({
        userData: []
      });
    });
}

render() {
  const {
    iconLoading,
    permissions,
    userData
  } = this.state;
  console.log(userData)
  return ( <>
    <Form>
    <Col xs = {24}
    xl = {12}
    className = "__border-right streams_partner_trackers" >
    {
      this.validator(
        'name',
        t('user_name'), <
        Input placeholder = {
          t('enter_user_name')
        }
        size = "large"
        value = {
          userData.user.name
        }
        />, [{
          required: true,
          message: t('message.field_is_required')
        }])
    } </Form> </>
  )
}


After fetch is completed, the data is in userData, but the error is TypeError: Cannot read property 'user' of undefined. How to properly render and toss value after fetch?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arslan Abaev, 2021-07-05
@ADDtvb

Do a ternary check directly on value

value = {
          userData.user.name ?  userData.user.name : "Loading..."
        }

And after that, the data from the API will arrive and display correctly for youuserData.user.name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question