I have created a login form in React that uses an Axios post request like this:
axios.post('http://localhost:8080/users/validate', {
email: email,
password: password,
})
.then((res) => {
setError(res.data);
//If validation passed
if (res.data.includes('Login successful')) {
navigate('/');
};
});
I would like to pass the res.data
from this post request to a different React component. Specifically being the Header component so I can display the text from res.data
.
This is the structure of the components in my React app
<>
<Header />
<Routes>
<Route path="/" element={<Index />}/>
<Route path="/results/:id" element={<Results />} /> {/* Passes route with ID from input */}
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register /> } />
<Route path="/users" element={<Users />}/>
<Route path="/products" element={<Products />}/>
<Route path="*" element={<Error />}/>
</Routes>
<Footer />
</>
With Login
being the component containing the res.data
and Header being the component I would like to send res.data
too.
Ill include the back-end for in case their is a method to send this to that component from the back-end but ideally I would like to do it through the front-end perhaps using an axios request.
app.post('/users/validate', (req, res) => {
const email = req.body.email;
const password = req.body.password;
if (email && password) {
//Check all emails against input
db.query(selectEmail, [email], (err, rows) => {
if (err) throw err;
if (rows.length > 0) {
//If password and email match then login
if (HashPassword(password, rows[0].salt) == rows[0].password) { //Checks password and compares to hash
res.send(rows[0].first_name);
}
else {
res.send('Incorrect password');
};
}
else {
res.send('Email or password are incorrect');
};
});
};
});
In a simplified version I want to send the first_name
row from my back end to the Header
component on my front-end. But I am struggling to understand how to do this because the post request containing first_name
is found under is currently being used under the Login
component.
CodePudding user response:
How about passing with the state
prop in useNavigate - hook as
axios
.post("http://localhost:8080/users/validate", {
email: email,
password: password,
})
.then((res) => {
setError(res.data);
//If validation passed
if (res.data.includes("Login successful")) {
navigate("/", {state: res.data}); // like so
}
});
and In Header
component you can get the value using useLocation hook
CodePudding user response:
You should use a state management library like Redux or React Context
With the state management library, you can access your state in all the components of your app.