vue.jsaxiosvue-composition-apivueuse

Post request with useAxios


I am trying to use the composition api on my Vue app, and I need to do a post request to my backend api. I am trying to make use of the "useAxios" utility from vueuse, but I can't figure out how to pass data into a post request. It isn't shown properly in the docs...

I want to convert the following axios request into one that uses "useAxios".

await axios.put(`/blog/posts/${route.params.postID}/`, post.value)
    .then(() => notification = "Post Created!")
    .catch(() => {
      error = "Failed to create post"
    });

I tried setting the value of the data field, but that didn't work...

const {data, execute, isFinished} = useAxios(axios)
data.value = post
await execute(`/admin/blog/posts/${route.params.postID}/`, {method: "PUT"})

I also tried passing the post object into the execute method as a parameter, but my ide complained.

Thanks in advance!


Solution

  • Set up your pending request ahead of time:

    const { data, execute, isFinished } = 
      useAxios(`/admin/blog/posts/${route.params.postID}/`, 
         { method: "PUT" }, 
         { immediate:false });
    

    Then in the future you can call it by passing the data as follows:

    const requestBody = { /* your data */ };
    await execute({ data: requestBody });