score:0

Accepted answer

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.

score:0

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.

score:4

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.


Related Query

More Query from same tag