0

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?

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.