Michael Fayez's avatar

SyntaxError: "undefined" is not valid JSON

SyntaxError: "undefined" is not valid JSON

export default function languageModel() { if (typeof window !== "undefined") { if (localStorage.getItem("language")) { const prevObj = JSON.parse(localStorage.getItem("language")); const keys = Object.keys(prevObj).map((item) => item .replaceAll("-", " ") .replaceAll(",", " ") .replaceAll(".", " ") .replaceAll("'", "") .replaceAll("!", "") .split(" ") .join("_") );

  const values = Object.values(prevObj);
  const generateNewArr = values.map((item, i) => {
    let newObj = {};
    newObj[keys[i]] = item;
    return newObj;
  });
  return Object.assign.apply(Object, generateNewArr);
}
return false;

} return false; }

0 likes
1 reply
LaryAI's avatar
Level 58

It seems like the issue is that localStorage.getItem("language") might be returning undefined if the "language" key does not exist in localStorage. When JSON.parse() is called with undefined, it throws a SyntaxError because undefined is not valid JSON.

To fix this, you should check if localStorage.getItem("language") is not null before attempting to parse it as JSON. Here's the corrected code:

export default function languageModel() {
  if (typeof window !== "undefined") {
    const languageItem = localStorage.getItem("language");
    if (languageItem) {
      const prevObj = JSON.parse(languageItem);
      const keys = Object.keys(prevObj).map((item) =>
        item
          .replaceAll("-", " ")
          .replaceAll(",", " ")
          .replaceAll(".", " ")
          .replaceAll("'", "")
          .replaceAll("!", "")
          .split(" ")
          .join("_")
      );

      const values = Object.values(prevObj);
      const generateNewArr = values.map((item, i) => {
        let newObj = {};
        newObj[keys[i]] = item;
        return newObj;
      });
      return Object.assign({}, ...generateNewArr);
    }
    return false;
  }
  return false;
}

Additionally, I've made a small change to the Object.assign.apply(Object, generateNewArr) line. Instead of using apply, you can spread the array directly into Object.assign using the spread syntax (...). This is a more modern and cleaner approach to merging objects in an array into a single object.

Remember to handle the case where localStorage.getItem("language") might return null by providing a default value or an appropriate fallback mechanism to ensure your application's robustness.

Please or to participate in this conversation.