TiernO
TiernO

Reputation: 447

Redirect from async function in react?

I have a function being called when a form is submitted which is like so:

import { API } from "aws-amplify";

export default (async function submitSite(values) {
  console.log(values);
  return API.post("sites", "/sites", {
    body: values
  })
});

After this function is done, how can I redirect to another page. I have tried using this.props.history.push and window.location.replace() after the api call but neither works.

Update

export default (async function submitSite(values) {

  try {
    await this.createSite({
      content: values
    });
    this.props.history.push("/");
  } catch (e) {
    alert(e);
  }

  createSite(site) {
    return API.post("notes", "/notes", {
      body: site
    });
  };
});

Upvotes: 1

Views: 2699

Answers (1)

Ana Goessens
Ana Goessens

Reputation: 36

When using an async function you can use await to wait for the promise to be resolved. You can then redirect using for example this.props.history.push('/path').

Upvotes: 0

Related Questions