Arunya
Arunya

Reputation: 291

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

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",
    }
  ]
}

Upvotes: 4

Views: 463

Answers (3)

laxman
laxman

Reputation: 2110

One possible solution would be to use some state management library such as redux.

Otherwise you will need to have a component that will do this fetching stuff and this component should be a common ancestor to the components that will be at least affected with the data changes from API.

My objective is how to pass the the user name while user is getting logged in. When User gets logged in then it should show "welcome Username".

As a more generic solution, you can create a HOC that will do the fetching API stuff and return a new component with the data from the API injected as props.

Upvotes: 0

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

You can do it like this:

axios
      .post(`/api/Login/auth`, data, {
        headers: { "Content-Type": "application/json" }
      })
      .then(res => {
        console.log(res);
        this.props.history.push("/Welcome", { ...res });
      })
      .catch(err => {
        console.log(err.response.data.message);
        var res = err.response.data.message;
        this.setState({ errorMsg: res });
      });

And as you are sending JSON Web Token as data, you can access it as:

this.props.data.item[0].firstName

Hope this works for you.

Upvotes: 4

Tharun208
Tharun208

Reputation: 103

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.

Upvotes: 0

Related Questions