简体   繁体   中英

How to i save a new entry in array to local storage?

I have an comoponent where i add a new playlist, I've made a function to add a playlist to the playlist array, but when i refresh the page, de new entry is gone. i have tried to save to localStroge, but it doesn't seem te work? how do i fix this? I also have a db.json file where i fetch the playlist data, can i possibly save there if localStorage wont work?

import axios from "axios";
import {
  Box,
  Button,
  CircularProgress,
  Stack,
  TextField,
  Typography,
} from "@mui/material";
import MIcons from "../Utils/MIcons";
import PlayLists, { PlayListValues } from "./PlayLists";

const Home = () => {
  const [playLists, setPlayLists] = useState<PlayListValues[]>([]);
  const [newList, setNewList] = useState("");

  useEffect(() => {
    try {
      axios.get(`http://localhost:3000/playList`).then((res) => {
        const response = res.data;
        setPlayLists(response);
      });
    } catch (err) {
      console.debug(err, "error");
    }
  }, []);

  const addPlayList = () => {
    if (newList) {
      let num = playLists?.length + 1;
      let newEntry = { id: num, title: newList, songs: [] };
      setPlayLists([...playLists, newEntry]);
    }
  };

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

  console.log(playLists, "playlist");

  return (
    <Box>
      <Stack direction="row" spacing={2} justifyContent="space-between" m={2}>
        <Stack direction="row" spacing={2}>
          <MIcons.LibraryMusic />
          <Typography variant="subtitle1">Your playlists</Typography>
        </Stack>
      </Stack>
      <Stack direction="row" spacing={2} m={2} justifyContent="center">
        {playLists && <PlayLists playList={playLists} />}
        {!playLists && <CircularProgress />}
      </Stack>
      <TextField
        label="Add playList"
        variant="outlined"
        value={newList}
        onChange={(e) => setNewList(e.target.value)}
      />
      <Button onClick={addPlayList}>add</Button>
    </Box>
  );
};

export default Home;

Just set the initial value from localStorage

const [playLists, setPlayLists] = useState<PlayListValues[]>(localStorage.getItem('playLists') || []);

You wrote an useEffect that render every change on your playList state, So when you refresh your browser the component render again and the playlist state got its initial value that is [] empty array the your useEffect called and set empty array in localStorage. So you should wrap your localStorage:setItem in a condition like below:

useEffect(() => {
    if(!!playLists.length){
localStorage.setItem("playLists", JSON.stringify(playLists));
}
  }, [playLists]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM