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);
} ```