Search code examples
javascriptreactjsinputlocal-storageuitextfield

add it to Localstorage so that it does not delete the recorded information when I go to and from the next page?


How do I add it to Localstorage so that it does not delete the recorded information when I go to and from the next page? full code

const [firstName, setFirstName] = useState("");
  const [lastname, setLastname] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
<Box sx={{ ml: "140px", mb: "30px" }}>
    {multipleInput.map((item) => {
      return (
        <Grid item sm={8}>
          <TextField
            sx={{ mt: "20px" }}
            autoComplete={item.autoComplete}
            fullWidth
            value={item.value}
            onChange={(e) => item.setValue(e.target.value)}
            label={item.label}
            InputLabelProps={{ style: { fontFamily: "Montserrat" } }}
            inputRef={item.inputRef}
            type={item.type}
          />
        </Grid>
      );
    })}
  </Box></Box>
  <Link href="TechSkill">
    <Button>
      <NavigateNextIcon />
    </Button>
  </Link>

Solution

  • If I understand correctly, you want to save the value of a variable to localStorage, and it's easy enough to do.

    You can use the useEffect hook, which will monitor the update of the variable and constantly update the localStorage.

    Saving looks like this:

    // SAVING
    useEffect(() => {
      // storing input name
      localStorage.setItem("phone", JSON.stringify(phone));
    }, [phone]);
    

    So, when a user will update the value of variable phone, the value in localStorage will be updated automatically.

    To read the value from the localStorage, do the following:

    // READING
    const [phone, setPhone] = useState(() => {
      // getting stored value
      const saved = localStorage.getItem("phone");
      const initialValue = JSON.parse(saved);
      return initialValue || "";
    });
    

    But for exact answer it's not clear what exactly you want to do, in general the variant described above should work if you tweak it.