Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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(); // Error occurs here 


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.
Posted
Updated 25-Sep-22 23:02pm

1 solution

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.

This is exactly right, the Stringify method is designed to convert key-value objects into JSON, not store functions etc. Instead if the API class contains functions that you need access to then you should store any state values as a child within that class. See this JSFiddle I put together as an example[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900