Basit Minhas
Basit Minhas

Reputation: 317

in React i need to get the state from local storage and then set another state conditionally based on this state

const  [isDone, setIsDone] = useState({
      customer: undefined, //need to set another state based on this state
      shipping: undefined,
      payment: undefined,
    });

    //Set values of isdone on page load from localstorage if exists else set to false
  useEffect(() => {
    setIsDone({
      customer: localStorage.getItem("customer")
      ? localStorage.getItem("customer")
      : false,
      shipping: localStorage.getItem("shipping")
      ? localStorage.getItem("shipping")
      : false,
      payment: localStorage.getItem("payment")
        ? localStorage.getItem("payment")
        : false,
    });

  //if customer section has not been done,set edit clicked to false
    !isDone.customer && setEditClicked({ ...editClicked, customer: true }); //This code block is 
    getting executed evey time,even though state of isDone.customer is set to "true".i confirmed from 
    react dev tools 
     //
      
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

Thing is IsDone.customer is saved to "true" in local storage, but still this code is not working.i even coverted it to boolen using Boolean method but still same result.

here is how i save data to localstorage.it is working, i have checked it.

const handleSubmit = (event) => {
const name = event.currentTarget.getAttribute("name");

//save isDone to local storage
localStorage.setItem(name, true);
setEditClicked({ ...editClicked, [name]: false });
 };

Upvotes: 0

Views: 200

Answers (2)

Denys Presich
Denys Presich

Reputation: 56

isDone state won't be changed immediately after setIsDone in useEffect

It would be better to create another constant inside useEffect

useEffect(() => {
    const isDone = {
      customer: localStorage.getItem("customer")
      ? localStorage.getItem("customer")
      : false,
      shipping: localStorage.getItem("shipping")
      ? localStorage.getItem("shipping")
      : false,
      payment: localStorage.getItem("payment")
        ? localStorage.getItem("payment")
        : false,
    }

    setIsDone(isDone);

    !isDone.customer && setEditClicked({ ...editClicked, customer: true });

  }, []);

Upvotes: 2

Wang Liang
Wang Liang

Reputation: 4444

http://prntscr.com/106dqqr

localStorage is working with string, So, you need use JOSN.parse, and JSON.stringfy

JSON.stringify(false)
"false"
JSON.parse("false")
false
var c = localStorage.getItem("customer")
var s = localStorage.getItem("shipping")
var p = localStorage.getItem("payment")

...
 setIsDone({
      customer: c
      ? JSON.parse(c)
      : false,
      shipping: s
      ? JSON.parse(s)
      : false,
      payment: p
        ? JSON.parse(p)
        : false,
    });

...
//save isDone to local storage
localStorage.setItem(name, JSON.stringfy(true));

Upvotes: 0

Related Questions