How to pass data from one component to another while using API in reactjs

Arunya :

In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in? When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "[email protected]",
      "password": "Aertyuio",
    }
  ]
}
Tharun208 :

Since you are using react-router push method. It also has the ability to send different props value along with your pathname and this push will work only on components wrapped in .

In your case, you need to pass a state along with your route name. Below changes, you have to pass state along with your route name in history.push.

this.props.history.push("/Welcome", { ...res }); on Login.js.

And get the response values on your Welcome.js by using this.props.location.state.firstName.

Attaching the document for your reference - https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md

And Also, I attached a basic demonstration of history.push in this - https://codesandbox.io/s/broken-flower-hbglx.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=15485&siteId=1