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