Hi, I am currently creating a login page with ReactJS. This page utilises an API which has an 'authorise' function confirming whether the entered details are authorised to use the API. To handle the API calls, I have created a class which has a function for each possible API call.
If the user is able to login successfully (if the authorise function returns a status of 200) they are redirected to a 'ProjectSelect' page/component. From this Project Select page the user will be able to select a specific project from their project list.
Now, here is where the problem lies. I need to now use the API instance from the 'Login' component in the 'ProjectSelect' component. The way in which I am currently trying to do this involves storing it in local storage as such:
Login.jsx:
import {API} from 'filepath';
const api = new API();
async function loginUser(email, password, appid) {
return api.authorise(email, password, appid);
}
export default function Login() {
const classes = useStyles();
const [email, setEmail] = useState();
const [password, setPassword] = useState();
const [appid, setAppId] = useState();
const handleSubmit = async e => {
e.preventDefault();
const response = await loginUser(
email,
password,
appid
);
console.log(response);
if (response.status === 200) {
swal("Success", "Logged In", "success", {
buttons: false,
timer: 2000,
})
.then((value) => {
localStorage.setItem('access_token', response.data.access_token);
localStorage.setItem('api', JSON.stringify(api));
window.location.href = "/bimpluslogin";
});
} else {
swal("Failed", "Login Failed", "error");
}
}
ProjectSelect.jsx:
const api = JSON.parse(localStorage.getItem('api'));
let allProjects = api.getAllProjects();
I am aware that if you JSON.stringify() an object it will only take the key values leaving it basically unusable when parsed back through the JSON.
What I have tried:
I have tried to create a new API instance in the ProjectSelect component and storing the auth details in local storage however that causes a lot of issues and doesn't allow me to use all of the functions.
I would appreciate any suggestions on how to store an object from one component and then use that exact same object in another component. Thanks in advance.