0

I am working on react app, Where generally user login and submit the form and in form ,there are mulitple fields, which is select i.e drop-down fields ,

whenever user logged in the system,

login = async (data = {}) => {
    try {
      // const { token, user } = await login(data);

      const { access_token, expires_at } = await login(data);
      const token = access_token;
      localStorage.setItem("token", token);
      const authToken = localStorage.getItem("token");

      const config = await getConfig(authToken);
      localStorage.setItem("config", JSON.stringify(config));

      initAxios();

      this.setState(
        {
          token,
        },
        () => {
          notify({
            type: "success",
            text: "Successfully logged in!",
          });
        }
      );
    } catch (error) {
      if (error.response.status === 401) {
        throw error;
      }
      notify({
        type: "error",
        text: getErrorMessage(error),
      });
    }
  };

I want to use this in my multiple form component where I can get this object,

What will be the best solution to retrieve the data from local storage ?

const configData = JSON.parse(localStorage.getItem("config"));
export const category = configData.category;
export const gender = configData.gender;
......



& import in From Component and use it ,

Can it is possible to use it in directly form component with the help of useEffect() hooks?

Adding Code Snippet @Arnab, here

if (localStorage.getItem("apiData")) { 
accessoriesConfig = JSON.parse(localStorage.getItem("apiData")); return accessoriesConfig; }
else{ 
return fetchOptions().then(response => localStorage.setItem("apiData", JSON.stringify(response)));
//this is returns me always promise as pending status ,that breaks my functionality 

} 
//API Call with axios
export async function fetchOptions() {
return getAxios("get","/api/config/") .then(response => response.data); 
} ```  
1
  • 1
    I didn't understand your question. Commented Jul 16, 2020 at 4:24

2 Answers 2

1

If you are getting json response from your api, then you can save the data in Localstorage by selector which will be easier for you to retrieve later.

axios({
    url: 'APIplaceholder'
    adapter: jsonpAdapter
  }).then((res) => {     
        localStorage["name"]=res.data.name
        localStorage["email"]=res.data.email
  });

In That case, when you will try to retrieve, you can just call localstorage.get() function by key like this::

localStorage.getItem("name")

Or else you can save the whole response as a string to localstorage like:

axios({
        url: 'APIplaceholder'
        adapter: jsonpAdapter
      })
.then((res) => {
     localStorage.setItem("apiData", JSON.stringify(res.data));
});

and retrieve like this:

var data = JSON.parse(localStorage.getItem("apiData"));

Then access them with dot(.) operator as an object. data.name

Sign up to request clarification or add additional context in comments.

10 Comments

PLeasure is mine. Hope the answer was helpful
Hi @Arnab , I am trying to save the api response on login of user , but I want to try below , ``` lang-js if (localStorage.getItem("apiData")) { accessoriesConfig = JSON.parse(localStorage.getItem("apiData")); return accessoriesConfig; }else{ return fetchOptions().then(response => localStorage.setItem("apiData", JSON.stringify(response))); this is returns me always promise as pending status ,that breaks my functionality } export async function fetchOptions() { return getAxios("get","/api/config/") .then(response => response.data); } ```
Can you share it as an answer or a different snippet with formatted? its difficult to understand now
Yeah ,I modified the post and added the code at bottom,In Comment section I cant highlight the code @Arnab
getAxios("get","/api/config/") .then(response => response.data); here after getting response from the API, you need to store it to localstorage
|
0

Solution I applied here is below,

export async function fetchOptions() {
    var configData = JSON.parse(localStorage.getItem("config"));
    if(configData){
      return configData;
    }else{
    return getAxios("get","/api/config/")
      .then(response => {      
        localStorage.setItem('config',JSON.stringify(response.data));
        return response.data;
      });
    }
  }


Importing in Components and Files.

import {fetchOptions} from '../../requests';
var configData = JSON.parse(localStorage.getItem("config"));
if(!configData) {
  fetchOptions().then(res => {
    setConfigValue(JSON.parse(localStorage.getItem("config")));
  });
}else{
  setConfigValue(configData);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.