D
D
dmitriu2562021-03-12 14:10:57
React
dmitriu256, 2021-03-12 14:10:57

Is the request asynchronous correctly?

Is the asynchronous request correctly framed in this component? Or compnentDidMount should be issued as a synchronous request, and the getUserName function should be left asynchronous?
1) The request in componentDidMount gets the post description from the server. We write the result in state
2) Request to get the user's login by its userId from the previous request. - method getUserName Post

request data looks like

{
  "userId": 1,
  "id": 2,
  "title": "qui est esse",
  "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}


The data to receive the user has the form
{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "[email protected]",...

Component code
constructor(props) {
        super(props);

        this.state = {
            post: {},
            author: ''
        };
    }


    async componentDidMount() {
        let id = this.props.match.params.id;

        try{
                const response = await axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
                const data = await response.data;
                const authorId = data.userId;

                this.setState({post: data});

                //Логин пользователя
                this.getUserName(authorId);
                
        } catch (e) {
            console.log(e);
        }
    }

//получение логина пользователя
    getUserName = async (id) => {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);

        if (!response.ok) {
            console.log(response.status);
        }
        const data = await response.json();
        const result = await data.username;
        this.setState({author: result});
    }

render() {
 return (
            <div style={postStyle}>
                <h1>Post Details {this.props.match.params.id}</h1>

                <h2>{this.state.post.title}</h2>
                <p>{this.state.post.body}</p>
                <div>
                    <span>User:
                        <Link to={'/users/' + this.state.post.userId}>{this.state.author}</Link>
                    </span>
                </div>
            </div>
        );
}


At the moment - the display of the post is noticeably "twitching" - it occurs due to the loading of data and the formation of state.
Reflection solution:
To smooth out the current moment, hang a preloader on the entire page and disable it when the state is formed, add the property load: true to the state and as soon as the request is successful, change its value.

But then there is a "glut" of preloaders in the application
on the users page - loading users
on the posts page - loading posts
opening a post - preloader.
How can this behavior be improved?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question