crimsonpython24
crimsonpython24

Reputation: 2383

Cloning Dictionaries in React JSX

I have a hard time finding the answer to this question. Say I have the following script (which doesn't work):

class ProfileCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: {},
    };
  }

  componentDidMount() {
    fetch("/accounts/api/" + username)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }
}

This is what result and this.state.items look like, respectively:

{last_login: "2020-06-25T09:50:24.218Z", is_superuser: "true", is_staff: "true", …}
{}

How can I make the this.state.items have the exact same content as result? Please assume that all variables and methods used have been declared.

Upvotes: 0

Views: 59

Answers (1)

Alice Arruda Atalla
Alice Arruda Atalla

Reputation: 21

how are you? How is your render()? Can you specify more your question? For me, the way to put the results inside the items is right, but it only sets the state and changes the content of items after rendering. Below an example:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      image: ''
    }
    this.urlImage = this.urlImage.bind(this);
  }

  urlImage() {
    fetch("https://dog.ceo/api/breeds/image/random")
      .then( (res) => res.json())
      .then((results) => this.setState({ image: results }))
  }


  componentDidMount() {
    this.urlImage()
  }

  render() {
    const { image } = this.state;
    if (image === '') return <h2>Loading...</h2>
    return (
      <div>
        <h2>Dogs!</h2>
        <div>
        <img src={image.message} alt={'Dog'}/>
        </div>
      </div>
    );
  }
}

Sorry if you understand that I do not interpret your question correctly, but want to complement that render() was used as an example to show that this.setState() is asynchronous, so with render() you can use this change of state, or you could use componentDidUpdate() that is also executed in the state receives a new value.

componentDidUpdate () {
  console.log (this.state.items)
}

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

In fact, you need to specify a question better, because a simple "my status is like this and I wish it could be like" this not described, I hope you can do what you want. Thanks!

Upvotes: 1

Related Questions