Pracede
Pracede

Reputation: 4361

How to get response header from axios fetch response?

I am build an VueJS application. I fetch data from wordpress rest api. I am not very experienced with javascript and VueJS.

  async getPosts({ state, commit, dispatch }) {
        if (state.posts.length) return
        try {
          let posts = await fetch(
            `${siteURL}/wp-json/wp/v2/posts?page=1&per_page=10&_embed=1`
          ).then(res => res.json())
           let total = res.headers['x-wp-total']
            console.log(total)
          posts = posts
            .filter(el => el.status === "publish")
            .map(({ id, slug, title, excerpt, date, tags, content, author, author_name  }) => ({
              id,
              slug,
              title,
              excerpt,
              date,
              tags,
              content,
              author,
              author_name
            }))



          commit("updatePosts", posts)

        } catch (err) {
          console.log(err)
        }

My code was working until i add these to lines :

 let total = res.headers['x-wp-total']
            console.log(total)

I want to get an header from my response to configuration my pagination. Here the error message i have : ReferenceError: res is not defined at _callee$ (VM770 app.js:5162) at tryCatch (VM768 commons.app.js:4486) at Generator.invoke [as _invoke] (VM768 commons.app.js:4712) at Generator.prototype. [as next] (VM768 commons.app.js:4538) at asyncGeneratorStep (VM768 commons.app.js:31) at _next (VM768 commons.app.js:53)

Thanks for your help. I think i need some courses to undertand some javascript basic concept. So any online documentation or courses is welcome.

Upvotes: 0

Views: 1273

Answers (1)

Nafiz Bayındır
Nafiz Bayındır

Reputation: 495

  1. res variable is scoped in the function that is provided as a callback to then.

  2. header variables can be accessed by using res.headers.get(string headerName)

 async getPosts({ state, commit, dispatch }) {
        if (state.posts.length) return
          fetch(
            `${siteURL}/wp-json/wp/v2/posts?page=1&per_page=10&_embed=1`
          ).then((res) => {

           let total = res.headers.get('x-wp-total')
           console.log(total)
           posts = res.json()
            .filter(el => el.status === "publish")
            .map(({ id, slug, title, excerpt, date, tags, content, author, author_name  }) => ({
              id,
              slug,
              title,
              excerpt,
              date,
              tags,
              content,
              author,
              author_name
            }))
           commit("updatePosts", posts)
          }).catch ((err) => {
          console.log(err)
          })

Upvotes: 1

Related Questions