我试图在react中设置localstorage,但是值未定义。
即使我使用JSON.stringify,它也不起作用。
我认为value
没有到达那里。
我的代码如下:
import fetch from "isomorphic-fetch";
import { API } from "../config";
import cookie from "js-cookie";
export const signup = (user) => {
return fetch(`${API}/signup`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(user),
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
// login
export const login = (user) => {
return fetch(`${API}/login`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(user),
})
.then((response) => {
console.log(user)
return response.json();
})
.catch((err) => console.log(err));
};
// logout
export const logout = (next) => {
removeCookie("token");
removeLocalStorage("user");
next();
return fetch(`$${API}/logout`, {
method: "GET",
})
.then((response) => {
console.log("Logged Out");
})
.catch((err) => console.log(err));
};
// set cookie
export const setCookie = (key, value) => {
if (process.browser) {
cookie.set(key, value, {
expires: 1,
});
}
};
// remove cookie
export const removeCookie = (key) => {
if (process.browser) {
cookie.remove(key, {
expires: 1,
});
}
};
// get cookie
export const getCookie = (key) => {
if (process.browser) {
return cookie.get(key);
}
};
// set localstorage
export const setLocalStorage = (key, value) => {
if (process.browser) {
localStorage.setItem(key, JSON.stringify(value));
}
};
// remove localstorage
export const removeLocalStorage = (key) => {
if (process.browser) {
localStorage.removeItem(key);
}
};
// authenticate user by passing data to cookie and localstorage
export const authenticate = (data, next) => {
setCookie("token", data.token);
setLocalStorage("user", data.user);
next();
};
export const isAuth = () => {
if (process.browser) {
const cookieChecked = getCookie("token");
if (cookieChecked) {
if (localStorage.getItem("user")) {
return JSON.parse(localStorage.getItem("user"));
} else {
return false;
}
}
}
};