admin管理员组

文章数量:1389903

I'm trying to create author info block for posts.

So I created a block and tried to use redux to get author info, but could get only author id:

const applyWithSelect = withSelect(
    (select, props) => {
        return {
            authorId: select('core/editor').getCurrentPostAttribute('author')
        }
    }
);

Then I tried to use apiFetch to get author info by its id:

const authorApi = apiFetch( { path: `/wp/v2/users/${authorId}` } ).then(data => {console.log(data)});

So it's actually working, I'm getting all author information in my console. But how to get that data values to map through it?

What should I insert inside then()? I think I should create an empty array and push that data values inside of it.

But I don't know how, my knowledge is not enough.

Can you help me, please?

I'm trying to create author info block for posts.

So I created a block and tried to use redux to get author info, but could get only author id:

const applyWithSelect = withSelect(
    (select, props) => {
        return {
            authorId: select('core/editor').getCurrentPostAttribute('author')
        }
    }
);

Then I tried to use apiFetch to get author info by its id:

const authorApi = apiFetch( { path: `/wp/v2/users/${authorId}` } ).then(data => {console.log(data)});

So it's actually working, I'm getting all author information in my console. But how to get that data values to map through it?

What should I insert inside then()? I think I should create an empty array and push that data values inside of it.

But I don't know how, my knowledge is not enough.

Can you help me, please?

Share Improve this question asked Apr 8, 2020 at 16:10 AslanAslan 557 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Finally, I found out how to do it. Just call fetchApi in componentDidMount and then create a new state in your component and add the response to this state when the request is done:

constructor(props) {
    super(props);
    this.state = {
      data: {},
    };
}
componentDidMount() {
    apiFetch( { path: '/wp/v2/users/1' } )
      .then(data => this.setState({ data }));
}

then in render:

const { data } = this.state;

finally in return for example avatar of author:

<div className={className}>
    { data.avatar_url ? (<img src={data.avatar_url['24']} />) : (<></>) }
</div>

本文标签: plugin developmentHow to use apiFetch to get author information in Gutenberg properly