Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

javascript - localStorage.setItem() At least 2 arguments required but only 1 passed

I'm trying to create a simple quest tracker in React, I want the checked value of true to persist in localStorage, but I'm getting this error. I understand that the arguments can only be strings so I tried JSON.stringify the boolean value but it still returns 1 argument. Here is the checkbox I've mapped to each quest in an array.

{props.mainQuests.map((quest, i) => {
    return (
        <div className="questlist">
            <li key={quest} className="quest">
                <p className="questName">{quest}</p>
                <p className="questDesc">{mainQuestDesc[i]}</p>
                <label for="completed">Completed</label>
                <input
                  type="checkbox"
                  name="completed"
                  id={quest}
                  onChange={props.toggleCheckboxChange}
                  autoComplete="off"
                ></input>
            </li>
        </div>
          );

And here is the function declared in the App.js component.

toggleCheckboxChange = (e) => {
    e.preventDefault();
    if (e.target.type === "checkbox") {
        const current = JSON.stringify(e.target.checked);
        console.log(e.target.id);
        console.log(current);
        localStorage.setItem({ [e.target.id]: current });
    }
  };

Both the console logs return string values, so I'm quite confused, any help would be greatly appreciated :)

question from:https://stackoverflow.com/questions/65936244/localstorage-setitem-at-least-2-arguments-required-but-only-1-passed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two ways to set a localStorage value, the first one being:

localStorage.setItem(e.target.id, current);

and the second one, perhaps even simpler:

localStorage[e.target.id] = current;

For more examples, see e.g. https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

And a note of interest, I see you are already doing this so that's good: localStorage will convert every value that is not a string by first doing .toString() on the value. As a result it is best to use JSON.stringify(obj) to store numbers, booleans, arrays and objects; and use let obj = JSON.parse(valueFromLocalStorage) to retrieve them again, which works for all object types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...