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); 
} ```  
Mehul
  • 21
  • 1
  • 9

2 Answers2

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

Arnab
  • 936
  • 7
  • 13
  • PLeasure is mine. Hope the answer was helpful – Arnab Jul 16 '20 at 04:38
  • 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); } ``` – Mehul Jul 16 '20 at 04:48
  • Can you share it as an answer or a different snippet with formatted? its difficult to understand now – Arnab Jul 16 '20 at 06:31
  • Yeah ,I modified the post and added the code at bottom,In Comment section I cant highlight the code @Arnab – Mehul Jul 16 '20 at 08:00
  • `getAxios("get","/api/config/") .then(response => response.data);` here after getting response from the API, you need to store it to localstorage – Arnab Jul 16 '20 at 12:46
  • `const configData = getAxios("get","/api/config/").then( response => { localStorage.setItem("config", JSON.stringify(response.data)) return response.data;} );` `console.log(configData);` `// THIS Will return me promise with pending status` `export const salutation = configData.salutation;` – Mehul Jul 17 '20 at 11:06
  • I can successfully set the values in local storage but,cant get the values from function,as its is returning me promise with pending state. – Mehul Jul 17 '20 at 11:08
  • Can you share your `response.data` please? – Arnab Jul 17 '20 at 18:59
  • { "accessories_city": { "ADILABAD": "ADILABAD", "AGRA": "AGRA", "MUMBAI":"MUMBAI" }, "salutation": { "MR": "Mr.", "MRS": "Mrs.", "MS": "Miss", "DR": "Dr." } } ``` This is the response – Mehul Jul 18 '20 at 04:52
  • Its because your function is returning value before getting data from axios. Make the function async like and then call axios as await. `const res = await axios('/data');` and ` return await res.json();` https://stackoverflow.com/questions/46733354/use-async-await-with-axios-in-react-js – Arnab Jul 18 '20 at 10:26
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);
}
Mehul
  • 21
  • 1
  • 9