admin管理员组

文章数量:1314058

I'm getting this error in my console. the last thing I did was registering a user! now I'm getting this error, I don't know why! I think it says that "user" is not a valid JSON how e? where I went wrong!

> Uncaught SyntaxError: "undefined" is not valid JSON
>     at JSON.parse (<anonymous>)
>     at ./src/context/Context.js (Context.js:5:1)
>     at options.factory (react refresh:6:1)
>     at __webpack_require__ (bootstrap:24:1)
>     at fn (hot module replacement:62:1)
>     at ./src/ponents/topbar/TopBar.jsx (SideMenu.jsx:23:1)
>     at options.factory (react refresh:6:1)
>     at __webpack_require__ (bootstrap:24:1)
>     at fn (hot module replacement:62:1)
>     at ./src/App.js (return-arrow.svg:26:1)

Context.js Where the error is. See const INITIAL_STATE

import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

Context Actions.js the same goes for login and it worked fine

export const RegisterStart = (userCredentials) => ({
  type: "REGISTER_START",
});

export const RegisterSuccess = (user) => ({
  type: "REGISTER_SUCCESS",
  payload: user,
});

export const RegisterFailure = () => ({
  type: "REGISTER_FAILURE",
});

The function in Register page

const handleSubmit = async (e) => {
    e.preventDefault();
    dispatch({ type: "REGISTER_START" });
    setError(false);
    try {
      const res = await axios.post("/register", {
        username,
        email,
        password,
        repeatPassword,
      });
      dispatch({ type: "REGISTER_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "REGISTER_FAILURE" });
      setError(true);
    }
  };

I'm getting this error in my console. the last thing I did was registering a user! now I'm getting this error, I don't know why! I think it says that "user" is not a valid JSON how e? where I went wrong!

> Uncaught SyntaxError: "undefined" is not valid JSON
>     at JSON.parse (<anonymous>)
>     at ./src/context/Context.js (Context.js:5:1)
>     at options.factory (react refresh:6:1)
>     at __webpack_require__ (bootstrap:24:1)
>     at fn (hot module replacement:62:1)
>     at ./src/ponents/topbar/TopBar.jsx (SideMenu.jsx:23:1)
>     at options.factory (react refresh:6:1)
>     at __webpack_require__ (bootstrap:24:1)
>     at fn (hot module replacement:62:1)
>     at ./src/App.js (return-arrow.svg:26:1)

Context.js Where the error is. See const INITIAL_STATE

import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

Context Actions.js the same goes for login and it worked fine

export const RegisterStart = (userCredentials) => ({
  type: "REGISTER_START",
});

export const RegisterSuccess = (user) => ({
  type: "REGISTER_SUCCESS",
  payload: user,
});

export const RegisterFailure = () => ({
  type: "REGISTER_FAILURE",
});

The function in Register page

const handleSubmit = async (e) => {
    e.preventDefault();
    dispatch({ type: "REGISTER_START" });
    setError(false);
    try {
      const res = await axios.post("/register", {
        username,
        email,
        password,
        repeatPassword,
      });
      dispatch({ type: "REGISTER_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "REGISTER_FAILURE" });
      setError(true);
    }
  };
Share Improve this question edited May 26, 2023 at 13:24 DINA TAKLIT 8,42810 gold badges83 silver badges90 bronze badges asked Aug 23, 2022 at 9:08 sultan.hsultan.h 4051 gold badge11 silver badges29 bronze badges 1
  • localStorage.getItem("user") is returning undefined – nullptr Commented Aug 23, 2022 at 9:10
Add a ment  | 

5 Answers 5

Reset to default 1

For me, I was getting this issue even though I check if there is an item but still getting the error Uncaught SyntaxError: "undefined" is not valid JSON and this because the local storage value was the string "undefined" rather then undefined it self that is why the condition if(item) was always verified. To fix this, I had to check also that item!=="undefined"

  const [state, setState] = useState(() => {
    const localStorageValue = window.localStorage.getItem(key)
    if (localStorageValue && localStorageValue !== 'undefined') {
      return JSON.parse(localStorageValue)
    }
    return typeof intialValue === 'function' ? intialValue() : intialValue
  })

Looks like you have no "user" entry in localStorage at the point of running this code.
Therefor, it throws an error since you are trying to JSON.parse an undefined value.

To make this work, we can check if "user" exists in localStorage before trying to parse it.

const INITIAL_STATE = {
  user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null,
  isFetching: false,
  error: false,
};

What we do here is first check if the return value of localStorage.getItem("user") is truthy and therefor not undefined.

If you want to be more explicit, you can also write it as -

user: localStorage.getItem("user") !== undefined ? JSON.parse(localStorage.getItem("user")) : null,

Your initial state is returning undefined initially because you are yet to set the item user. You can first check if user exist in localStorage: yes => return user else, return a default value of null

const INITIAL_STATE = {
  user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
 error: false,
};

try replacing:

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

by:

const INITIAL_STATE = {
  user: localStorage.getItem("user")? JSON.parse(localStorage.getItem("user")) : null,
  isFetching: false,
  error: false,
};

So I cleared the browser cache and it worked fine

本文标签: javascriptquotundefinedquot is not valid JSONStack Overflow